/**
 * @file	at_command.c
 * @author	chensj0621
 * @brief	
 * @version	0.1
 * @date	2021-11-11
 * @copyright Copyright (c) 2020, CHIPSEA Co., Ltd.
 * @note
 */

/*********************************************************************
 * INCLUDES
 */
#include "at_command.h"
void at_linkdata(uint8_t *data,uint8_t len);

at_cm_t at_data;

//AT命令表-需要在回调函数里面做数据非法判断
//可选参数个数当前只支持1个，因为协议里面只有1个
const at_cmd_handle_t at_cmd_tb[]=
{
    /*AT指令       指令长度     ble通道使能     必选参数个数  可选参数个数  回调函数*/
    {"+RST",       4,          TRUE,             0,           0,     (void *) at_rst             },//复位芯片
    {"+VER",       4,          TRUE,             0,           0,     (void *) at_ver             },//查询版本号
    {"+BAUD",      5,          TRUE,             1,           0,     (void *) at_baud            },//查询/设置波特率
    {"+MAC",       4,          TRUE,             1,           0,     (void *) at_mac             },//设置/查MAC地址
    {"+ADVEN",     6,          TRUE,             1,           0,     (void *) at_adven           },//设置/查广播状态
    {"+ADVIN",     6,          TRUE,             1,           0,     (void *) at_advin           },//设置/查广播间隔
    {"+CONNIN",    7,          TRUE,             1,           0,     (void *) at_connin          },//设置/查连接间隔
    {"+ROLE",      5,          FALSE,            1,           0,     (void *) at_role            },//设置/查设备角色
    {"+POWER",     6,          TRUE,             1,           0,     (void *) at_power           },//设置/查发送功率
    {"+NAME",      5,          TRUE,             1,           0,     (void *) at_name            },//设置/查设备蓝牙名
    {"+SCAN",      5,          TRUE,             1,           0,     (void *) at_scan            },//开启一次扫描
    {"+CANCELSCAN",11,         TRUE,             1,           0,     (void *) at_cancel_scanen   },//取消扫描
    {"+LINK",      5,          TRUE,             1,           0,     (void *) at_link            },//连接指定设备
    {"+GETSTAT",   8,          TRUE,             0,           0,     (void *) at_getstat         },//查询设备连接状态
    {"+DISC",      5,          TRUE,             2,           0,     (void *) at_disc            },//断开设备
    {"+CONNLIST",  9,          TRUE,             0,           0,     (void *) at_connlist        },//查询连接设备列表
    {"+SETFILT",   8,          TRUE,             1,           0,     (void *) at_setfile         },//查询/设置扫描过滤广播名
    {"+CLRFILT",   8,          TRUE,             0,           0,     (void *) at_clrfile         },//清除扫描过滤广播名
    {"+RESTORE",   8,          TRUE,             0,           0,     (void *) at_restore         },//恢复出厂设置
    {"+OTA",       4,          TRUE,             0,           0,     (void *) at_ota             },//进入OTA
    {"+SLEEP",     6,          TRUE,             0,           0,     (void *) at_sleep           },//进入sleep
    {"+AUTOLINKCFG",12,        TRUE,             2,           0,     (void *) at_autolinkcfg     },//连接指定设备
    {"+AUTOLINK",  9,          TRUE,             2,           1,     (void *) at_autolink        },//设置/查询自动连接
    {"+CLRLINK",   8,          TRUE,             1,           0,     (void *) at_clrlink         },//删除自动连接信息
    {"+SERVICE",   8,          FALSE,            5,           1,     (void *) at_service         },//设置/查询服务
    {"+TXHANDLE",  9,          TRUE,             2,           0,     (void *) at_txhandle        },//设置数据方向
    {"+BRIDGE",    7,          TRUE,             2,           4,     (void *) at_bridge          },//设置桥接模式
    {"+CLRBRIDGE", 10,         TRUE,             1,           0,     (void *) at_clrbridge       },//删除桥接模式通道
    {"+RSSI",      5,          TRUE,             1,           0,     (void *) at_rssi            },//设置RSSI过滤
    {"+CLRRSSI",   8,          TRUE,             0,           0,     (void *) at_clrrssi         },//清除RSSI过滤
    //{"+DATA",      5,          TRUE,             1,           0,     (void *) at_linkdata        },//查询已连接设备信息
    //{"+CONNSTAT",  9,          TRUE,             1,           0,     (void *) at_linkdata        },//查询已连接设备信息
    //{"+RXHANDLE",  9,          TRUE,             2,            0,     (void *) at_linkdata        },//查询已连接设备信息
    /* 结束项 */
    { "0", NULL },
};

void at_command_process(uint8_t *data, uint8_t len, uint8_t type)
{
    at_func at_cb;
    const at_cmd_handle_t *this_at_tb;
    this_at_tb = (at_cmd_handle_t *)&at_cmd_tb;
    uint8_t ret = 0;
    at_data.data_type = type;
    for(int k = 0 ; k < len ; k ++)
    {
        LOG("%c",*(data+k));
    }
    LOG("\r\n");
    for(int i = 0 ; i < len ; i ++)
    {
        if((*(data + i) == 'A')&&(*(data + i + 1) == 'T'))
        {
            //LOG("*(data + %d) = %c | %c\n",i,*(data + i),*(data + i + 2));
            for(;;this_at_tb++)
            {
                if(osal_memcmp(this_at_tb->at, "0", 1))
                {
                    break;
                }
                else if(osal_memcmp((data + i + 2), this_at_tb->at, this_at_tb->at_len))
                {   
                    ret = get_at_cmd_error(data, len, this_at_tb,i);
                    if(ret == AT_CMD_ERROR)
                    {
                        LOG("cmd error!\n");
                        return;
                    }
                    if((at_data.data_type == AT_BLE)&&(this_at_tb->ble_enable == FALSE))
                    {
                        LOG("FALSE error!\n");
                        return;
                    }
                    
                    at_cb = (at_func)this_at_tb->cb;
                    at_cb(data,len);
                    this_at_tb = (at_cmd_handle_t *)&at_cmd_tb;//指针回到起点，准备检查下一个AT命令
                    at_data.at_cmd_flag = 1;
                    break;
                }
            }
        }
    }
}
//回复数据
void at_send_data(uint8_t type,uint8_t *data,uint8_t len)
{

    //LOG("ble len %d\n",len);
    //LOG_DUMP_BYTE(data,len);
    if(type == AT_UART)
    {
        while(HalUartGetTxReady(UART1) == ERR_BUSY);
        HalUartSendBuf(UART1, data, len);
    }
    else if(type == AT_BLE)
    {
        //LOG("-----------------");
        //attHandleValueNoti_t notify_data;

        //osal_memcpy(sendMsg.handleValueNoti.value, data, len); 
        //sendMsg.handleValueNoti.len += len;
        
        if(notify_fifo_len >= BLE_NOTIFY_FIFO_LEN )
        {
            notify_fifo_len = 0 ;
            return ;
        }
        osal_memcpy((notify_fifo+notify_fifo_len), data, len); 
        //LOG_DUMP_BYTE(notify_fifo,20);
        notify_fifo_len += len;
        LOG("notify_fifo_len %d\n",notify_fifo_len);
        
        ble_task_set(USER_TASK_START, BLE_NOTIFY_FIFO_EVT, NULL);
        
       // bleuart_Notify_AT(at_data.data_type_index,&sendMsg.handleValueNoti);
    }
}

//设置AT模块的模式
void ble_set_at_mode(uint8_t at_mode)
{
    if(at_mode > 2)
    {
        return;
    }
    user_data.blemode = at_mode;
    if(user_data.blemode == BLE_ONLY_SLAVE)
    {
        ble_set_slave_num(0);//单从模式下，从机数量为0
        ble_set_master_num(1);//单从模式下，主机数量为1
    }
    else if(user_data.blemode == BLE_ONLY_MASTER)
    {
        ble_set_slave_num(8);//主机模式下，从机数量为8
        ble_set_master_num(0);//主机模式下，主机数量为0
    }
    else if(user_data.blemode == BLE_MASTER_AND_SLAVE)
    {
        ble_set_slave_num(8);//主机模式下，从机数量为8
        ble_set_master_num(2);//主机模式下，主机数量为2
    }
    user_data_save();
    LOG("g_masterMaxNum %d g_slaveMaxNum %d\n",g_masterMaxNum, g_slaveMaxNum);
}

uint8_t ble_set_ok_flag(uint8_t flag)
{
    if((flag !=0)&&(flag != 1))
    {
        return AT_CMD_ERROR;
    }
    at_data.ok_flag = flag;

    return AT_CMD_SUCCES;
}

uint8_t ble_get_ok_flag(void)
{
    //LOG("at_data.ok_flag=%d\n",at_data.ok_flag);
    return at_data.ok_flag;
}

//获取AT模块的模式
uint8_t ble_get_at_mode(void)
{
    return user_data.blemode;
}

//设置广播
uint8_t ble_set_adv_enable(uint8_t enable)
{
    uint8_t temp_mode = ble_get_at_mode();
    if(enable == TRUE)
    {
        
        if((temp_mode != BLE_ONLY_MASTER)&&(ble_get_master_link_num() != ble_get_master_num()))///主机模式下不允许开广播&&已经连接满了就不能开广播
        {
            LOG("adv is open !\n");
            ble_task_set(USER_TASK_START, START_ADVERT_EVT, NULL);//重新发广播，这里需要发事件开启广播，因为底层和应用是异步的
        }
        else
        {
            LOG("adv error !\n");
            return AT_CMD_ERROR;
        }
    }
    else if(enable == FALSE)
    {
        uint8 initial_advertising_enable = FALSE;
        GAPMultiRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8), &initial_advertising_enable, 0);
        LOG("adv is shut down\n");
    }
    return AT_CMD_SUCCES;
}

//判断AT命令是否非法
uint8_t get_at_cmd_error(uint8_t *data, uint8_t len,const at_cmd_handle_t *at,uint8_t idx)
{
    uint8_t temp_num = 0;
    uint8_t temp_flag = 0;
    //LOG("at_data.data_type %d\n",at_data.data_type);
    //判断参数个数是否非法
    for(int i = 0 ; i < len ; i ++)
    {
    
        if((*(data+i) == '<')&&(*(data+i-1) != ':')&&(temp_num == 0))//':'后面跟着都不是< 非法
        {
            LOG("error !\n");
            return AT_CMD_ERROR;
        }
        if(*(data+i) == '<')//找到'<'
        {
            temp_flag = 1;
            for(int j = 1 ; j < len - i ; j ++)
            {
                //LOG("j %d,flag %d *(data+i+j) %c\n",j,temp_flag,*(data+i+j));
                if(*(data+i+j) == '<')//还没找到>就又发现了< ，非法
                {
                    LOG("error !!\n");
                    return AT_CMD_ERROR;
                }
                else if(*(data+i+j) == '>')//找到'>'凑齐一个<>
                {
                    //LOG("*(data+i+j+1) %c %c\n",*(data+i+j+1),*(data+i+j+2));
                    //LOG("i = %d")
                    if((at_data.data_type  == AT_UART)&&(*(data+i+j+1) == ',')&&(*(data+i+j+2) != '<')||(at_data.data_type  == AT_UART)&&(*(data+i+j+1) != ',')&&(*(data+i+j+1) != '\r')&&(*(data+i+j+2) != '\n'))
                    {
                        LOG("AT_UART error !!!\n");
                        return AT_CMD_ERROR;
                    }
                    else if((at_data.data_type  == AT_BLE)&&(*(data+i+j+1) == ',')&&(*(data+i+j+2) != '<'))
                    {
                        LOG("AT_BLE error !!!\n");
                        return AT_CMD_ERROR;
                    }

                    for(int err_str_check = i+1 ;err_str_check < (i+j); err_str_check++)//检查<>内的非法字符
                    {
                        //LOG("*(data+err_str_check) %c\n",*(data+err_str_check));
                        if(((*(data+err_str_check) < '0')||((*(data+err_str_check) > '9')&&(*(data+err_str_check)<'A'))
                        ||((*(data+err_str_check)>'F')&&(*(data+err_str_check)<'a'))
                        ||(*(data+err_str_check)>'f'))&&(*(data+err_str_check)!='S')&&(*(data+err_str_check)!='M')
                        &&(osal_memcmp(at->at, "+NAME", at->at_len)==0)
                        &&(osal_memcmp(at->at, "+SETFILT", at->at_len)==0)
                        &&(osal_memcmp(at->at, "+RSSI", at->at_len)==0))
                        {
                            LOG("err_str_check\n");
                            return AT_CMD_ERROR;
                        }
                    }

                    temp_num ++;
                    i = i + j;//已经找过的就不用找了
                    break;
                }
                else if(j == len - i - 1)//找完了还没找到> ,非法
                {
                    LOG("error !!!!\n");
                    return AT_CMD_ERROR;
                }
                temp_flag = 0;
            }
        }
        else if((*(data+i) == '>')&&(temp_flag == 0))//没找到<就发现> 非法
        {
            LOG("error !!!!!\n");
            return AT_CMD_ERROR;
        }
        
    }

    //检查参数个数
    if((temp_num != at->must_param_num)&&(temp_num != 0)&&(at->optional_param_num == 0))//参数个数不对，非法  //可选参数后面再加
    {
        //必选参数个数或者0参数(即查动作)为不非法
        LOG("error !!!!!! temp_num %d\n",temp_num);
        return AT_CMD_ERROR;
    }
    else if((temp_num != 0)&&(at->optional_param_num != 0)&&((temp_num != (at->must_param_num+at->optional_param_num))&&(temp_num != (at->must_param_num))))
    {
        LOG("optional error !!!!!!\n");
        return AT_CMD_ERROR;
    }
    else if((temp_num == 0)&&(at_data.data_type  != AT_BLE))//没有参数的情况下，检查是否合法
    {
        //LOG("*(data+at->at_len + 2) %d *(data+at->at_len + 3) %d,at->at_len %d\n",*(data+at->at_len +idx+ 2),*(data+at->at_len +idx+ 3),at->at_len);
        if((*(data+at->at_len + idx + 2) != '\r')&&(*(data+idx+at->at_len + idx + 3) != '\n'))
        {
            LOG("num error !\n");
            return AT_CMD_ERROR;
        }
    }

    //LOG("temp_num %d temp_num_opt %d\n",temp_num,temp_num_opt);

    return AT_CMD_SUCCES;

}

//获取AT命令中的数据，只能获取一个字节数据
uint8_t get_at_data_1byte(uint8_t *data,uint8_t len)
{
    for(int i = 0; i<len; i++)
    {
        if((*(data + i) == ':')&&((*(data + i + 1) == '<')))
        {
            //if(( *(data+i+3) != '>')||((*(data+i+4) !='\r')&&(*(data+i+4) !='\n')))//超过1个字节，非法
            if(*(data+i+3) != '>')//超过1个字节，非法
            {
                return AT_CMD_ERROR;
            }
            
            return *(data+i+2)-0x30;
        }
        //LOG("str %c\n",*(data + i));
    }
    return AT_CMD_FIND;//没找到要设置的数据，回复0x7f表示查询
}
//获取AT命令中的mac地址
uint8_t get_at_data_only_mac(uint8_t *data,uint8_t len, uint8_t *mac)
{
    uint8_t temp_flag =0 ;
    uint8_t temp_mac[12] = {0};
    for(int i = 0; i<len; i++)
    {
        if((*(data + i) == ':')&&((*(data + i + 1) == '<')))
        {
            temp_flag = i+2;
        }
    }
    for(int j = 0; j < 12 ; j++)
    {
        temp_mac[j] = *(data+temp_flag+j);

        if((j==11)&&(*(data+temp_flag+j+1)!='>'))
        {
            return AT_CMD_ERROR;
        }
        
        //LOG("*(buff+j) %d %x\n",j , *(buff+j));
    }

    for(char i=0; i<12; i++)
    {
        if( (temp_mac[i] >= '0') && (temp_mac[i] <= '9') )
        {
            mac[5-(i>>1)] |= (temp_mac[i]-'0')<<((i%2)?0:4);
        }
        else if( (temp_mac[i] >= 'A') && (temp_mac[i] <= 'F') )
        {
            mac[5-(i>>1)] |= (temp_mac[i]-'A'+0x0A)<<((i%2)?0:4);
        }
        else if( (temp_mac[i] >= 'a') && (temp_mac[i] <= 'f') )
        {
            mac[5-(i>>1)] |= (temp_mac[i]-'a'+0x0A)<<((i%2)?0:4);
        }
        else
        {
            break;
        }
    }
    return 0;
}

//str：要回复的字符 len :字符的长度
//data：要回复的数据  data_len 数据的长度
void reply_at_data(uint8_t *str ,uint8_t len, uint8_t *data,uint8_t data_len)
{
    uint8 temp_data[204] = {0};
    if((len > 20)||(data_len > 180))
    {
        return ;
    }
    for(char i = 0 ; i <len ; i ++)
    {
        temp_data[i] = *(str + i);
    }
    temp_data[len] = '<';
    for(char j = 0 ; j < data_len  ; j++)
    {
        temp_data[len+j+1]  = *(data + j);
    }

    temp_data[len+data_len+1]  = '>';
    temp_data[len+data_len+2]  = '\r';
    temp_data[len+data_len+3]  = '\n';

    //while(HalUartGetTxReady(UART1) == ERR_BUSY);
    //HalUartSendBuf(UART1, temp_data, len+data_len+4);
    at_send_data(at_data.data_type,temp_data,len+data_len+4);
}

//回复OK
void reply_ok(uint8_t type)
{
    
    if(type == AT_UART)
    {
        //while(HalUartGetTxReady(UART1) == ERR_BUSY);
        //HalUartSendBuf(UART1, "OK\r\n", 4);
        at_send_data(AT_UART,"OK\r\n",4);
    }
    else if(type == AT_BLE)
    {
        //attHandleValueNoti_t notify_data;
        uint8_t notify_data[4];
        LOG("ble ok\n");
        notify_data[0] = 'O';
        notify_data[1] = 'K';
        notify_data[2] = '\r';
        notify_data[3] = '\n';
        //notify_data.len = 4;
   
        //bleuart_Notify_AT(at_data.data_type_index,&notify_data);
        at_send_data(AT_BLE,notify_data,4);
        //bleuart_Notify(at_data.data_type_index,&notify_data);
    }

}

//复位
void at_rst(uint8_t *data,uint8_t len)
{
    reply_ok(at_data.data_type);
    GAPMultiRole_TerminateConnection(GAP_CONNHANDLE_ALL);
    NVIC_SystemReset();
}

//查版本号
void at_ver(uint8_t *data,uint8_t len)
{
    uint8 temp_data[10];
    temp_data[0] = 'V';
    temp_data[1] = 'E';
    temp_data[2] = 'R';
    temp_data[3] = ':';
    temp_data[4] = 'V';
    temp_data[5] = (AT_VERSION / 100 % 10) + 0x30;
    temp_data[6] = (AT_VERSION / 10 % 10) + 0x30;
    temp_data[7] = (AT_VERSION / 1 % 10) + 0x30;
    temp_data[8] = '\r';
    temp_data[9] = '\n';

    //while(HalUartGetTxReady(UART1) == ERR_BUSY);
    //HalUartSendBuf(UART1, temp_data, 10);
    at_send_data(at_data.data_type,temp_data,10);
}

//设置波特率
void at_baud(uint8_t *data,uint8_t len)
{
    uint8_t temp_data = 0;
    uint8_t temp_baud = 0;
    
    temp_data = get_at_data_1byte(data,len);
    LOG("at_baud  temp_data %d\n\r",temp_data);
    if((temp_data > 4)&&(temp_data != AT_CMD_FIND))
    {
        return;
    }
    //LOG("user_data.baud %d\n",user_data.baud);
    if(temp_data == AT_CMD_FIND)//查询命令
    {
        temp_baud = user_data.baud + 0x30;//转换成ASCII码
        reply_at_data("BAUD:", 5, &temp_baud, 1);
    }
    else
    {
        reply_ok(at_data.data_type);
        user_data.baud = temp_data;
        while(HalUartGetBusy(UART1) == ERR_BUSY);
        HalUartBaudSet(UART1, baud_table[user_data.baud]);
    }
    user_data_save();
}

//设置/查询mac地址
void at_mac(uint8_t *data,uint8_t len)
{
    uint8_t temp_data = 0;
    uint8_t ret = 0;
    uint8_t temp_ble_mac[6] = {0};

    temp_data = get_at_data_1byte(data,len);
    //此处不检查非法，由后面检查非法，因为mac地址有12个字符
    if(temp_data == AT_CMD_FIND)//查询mac地址
    {
        LL_ReadBDADDR(temp_ble_mac);
        reply_at_data("MAC:",4,(uint8_t*)bdAddr2Str(temp_ble_mac),12);
    }
    else//设置mac地址
    {
        ret = get_at_data_only_mac(data,len,temp_ble_mac);
        if(ret == AT_CMD_ERROR)//非法，退出
        {
            return;
        }
        ble_set_adv_enable(FALSE);
        osal_memcpy(user_data.mac, temp_ble_mac, B_ADDR_LEN); //保存掉电不丢的结构体
        LL_WriteBDADDR(temp_ble_mac);//写mac地址
        ble_set_adv_enable(TRUE);
        user_data_save();//写flash
        reply_ok(at_data.data_type);
    }
}

//设置/查询广播状态
void at_adven(uint8_t *data,uint8_t len)
{
    uint8_t temp_data = 0;
    uint8_t temp_adv_state = 0;
    uint8_t ret = 0;
    temp_data = get_at_data_1byte(data,len);
    if(temp_data == AT_CMD_ERROR)//非法
    {
        return;
    }
    if(temp_data == AT_CMD_FIND)//查询广播状态
    {   
        GAPMultiRole_GetParameter(GAPROLE_ADVERT_ENABLED, &temp_adv_state, 0);
        temp_adv_state += 0x30;
        reply_at_data("ADVEN:", 6, &temp_adv_state, 1);
    }
    else if(temp_data == 0)//关
    {
        ret = ble_set_adv_enable(FALSE);
        if(ret != AT_CMD_ERROR)
        {
            reply_ok(at_data.data_type);
        }
    }
    else if(temp_data == 1)//开
    {
        ret = ble_set_adv_enable(TRUE);

        if(ret != AT_CMD_ERROR)
        {
            reply_ok(at_data.data_type);
        }
        
    }
}

//设置/查询广播间隔
void at_advin(uint8_t *data,uint8_t len)
{
    uint8_t temp_data = 0;
    uint8_t temp_advin = 0;
    temp_data = get_at_data_1byte(data,len);
    if((temp_data > 8)&&(temp_data !=AT_CMD_FIND))
    {
        return;
    }

    if(temp_data == AT_CMD_FIND)//查询命令
    {
        temp_advin = user_data.advin + 0x30;//转换成ASCII码
        reply_at_data("ADVIN:", 6, &temp_advin, 1);
    }
    else
    {
        uint8_t temp_mode = ble_get_at_mode();

        if(temp_mode != BLE_ONLY_MASTER)//主机模式下不允许设置广播间隔
        {
            reply_ok(at_data.data_type);
            ble_set_adv_enable(FALSE);
            ble_set_adv_enable(TRUE);
            user_data.advin = temp_data;
            //user_data_save();
            // Set advertising interval
            GAP_SetParamValue(TGAP_LIM_DISC_ADV_INT_MIN, advin_table[user_data.advin]);//设置广播间隔（PS：这里是设置从机的广播）
            GAP_SetParamValue(TGAP_LIM_DISC_ADV_INT_MAX, advin_table[user_data.advin]);
            GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MIN, advin_table[user_data.advin]);
            GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MAX, advin_table[user_data.advin]);
            GAP_SetParamValue(TGAP_CONN_ADV_INT_MIN, advin_table[user_data.advin]);
            GAP_SetParamValue(TGAP_CONN_ADV_INT_MAX, advin_table[user_data.advin]);
        }
 
    }
}
//设置/查询连接间隔
void at_connin(uint8_t *data,uint8_t len)
{
    uint8_t temp_data = 0;
    uint8_t temp_connin = 0;
    temp_data = get_at_data_1byte(data,len);
    if((temp_data > 6)&&(temp_data !=AT_CMD_FIND))
    {
        return;
    }

    if(temp_data == AT_CMD_FIND)//查询命令
    {
        temp_connin = user_data.connin + 0x30;//转换成ASCII码
        reply_at_data("CONNIN:", 7, &temp_connin, 1);
    }
    else
    {
        reply_ok(at_data.data_type);

        user_data.connin = temp_data;
        LOG("temp_connin %d\n",temp_data);
        user_data_save();
        // Set advertising interval
        osal_set_event(gapRole_TaskID, START_CONN_UPDATE_EVT);
    }
}

//设置/查询设备角色
void at_role(uint8_t *data,uint8_t len)
{
    uint8_t temp_data = 0;
    uint8_t temp_role = 0;
    temp_data = get_at_data_1byte(data,len);

    if((temp_data > 2)&&(temp_data !=AT_CMD_FIND))
    {
        return;
    }

    if(temp_data == AT_CMD_FIND)//查询命令
    {
        temp_role = ble_get_at_mode() + 0x30;//转换成ASCII码
        reply_at_data("ROLE:", 5, &temp_role, 1);
    }
    else
    {
        reply_ok(at_data.data_type);
        LOG("set role %d\n",temp_data);
        ble_set_at_mode(temp_data);
        GAPMultiRole_TerminateConnection(GAP_CONNHANDLE_ALL);
        NVIC_SystemReset();
    }
    
}

//设置/查询发送功率
void at_power(uint8_t *data,uint8_t len)
{
    uint8_t temp_data = 0;
    uint8_t temp_power = 0;
    temp_data = get_at_data_1byte(data,len);

    if((temp_data > 4)&&(temp_data !=AT_CMD_FIND))
    {
        return;
    }

    if(temp_data == AT_CMD_FIND)//查询命令
    {
        temp_power = user_data.power + 0x30;//转换成ASCII码
        reply_at_data("POWER:", 6, &temp_power, 1);
    }
    else
    {
        reply_ok(at_data.data_type);
        LOG("set pwer %d\n",temp_data);
        user_data.power = temp_data;
        rf_phy_set_txPower(power_table[user_data.power]);
        g_rfPhyTxPower = power_table[user_data.power];
        user_data_save();

    }
}
uint8_t get_at_sacn_data(uint8_t *data,uint8_t len)
{
    uint8_t temp_data  = 0;
    for(int i = 0 ; i < len ; i ++)
    {

        if((*(data + i) == ':')&&(*(data + i + 1) == '<'))
        {
            if((*(data + i + 3) == '>')&&(*(data + i + 2) >= '0')&&(*(data + i + 2) <= '9'))//个位数
            {
                temp_data = *(data + i + 2) - 0x30;
                break;
            }
            else if((*(data + i + 4) == '>')&&(*(data + i + 2) >= '0')&&(*(data + i + 2) <= '9')
            &&(*(data + i + 3) >= '0')&&(*(data + i + 3) <= '9'))//十位数
            {
                temp_data = (*(data + i + 2) - 0x30)*10+(*(data + i + 3) - 0x30);
                break;
            }
            else
            {
                return AT_CMD_ERROR;
            }
        }
        else if(i == (len - 1))//找完了还没找到数据，表示要查询
        {
            return AT_CMD_FIND;
        }
    }
    
    return temp_data;
}

//发起扫描
void at_scan(uint8_t *data,uint8_t len)
{
    uint8_t temp_data = 0;
    uint8_t temp_mode = ble_get_at_mode();
    
    if(temp_mode == BLE_ONLY_SLAVE)//单从机下不允许扫描
    {
        return ;
    }

    temp_data = get_at_sacn_data(data,len);
    
    if((temp_data == AT_CMD_ERROR)||((temp_data > 30)&&(temp_data != AT_CMD_FIND)))//超过30秒无事发生,非法
    {
        LOG("at scan error\n");
        return;
    }
    LOG("at scan data %d\n",temp_data);
    if(temp_data == AT_CMD_FIND)
    {
        uint8_t temp_scan_data[16] = {0};
        uint32_t temp_time = osal_get_timeoutEx(gapTaskID,GAP_OSAL_TIMER_SCAN_DURATION_EVT);
        temp_scan_data[0] = 'S';
        temp_scan_data[1] = 'C';
        temp_scan_data[2] = 'A';
        temp_scan_data[3] = 'N';
        temp_scan_data[4] = ':';
        temp_scan_data[5] = '<';
        temp_scan_data[6] = (at_data.sacn_time / 10 % 10) + 0x30;
        temp_scan_data[7] = (at_data.sacn_time / 1 % 10) + 0x30;
        temp_scan_data[8] = '>';
        temp_scan_data[9] = ',';
        temp_scan_data[10] = '<';
        temp_scan_data[11] = (temp_time / 10000 % 10) + 0x30;
        temp_scan_data[12] = (temp_time / 1000 % 10) + 0x30;
        temp_scan_data[13] = '>';
        temp_scan_data[14] = '\r';
        temp_scan_data[15] = '\n';

        //while(HalUartGetTxReady(UART1) == ERR_BUSY);
        //HalUartSendBuf(UART1, temp_scan_data, 16);
        at_send_data(at_data.data_type,temp_scan_data,16);

    }
    else if(temp_data != 0)
    {
        LOG("at scan! %d\n",temp_data);

        at_data.sacn_time = temp_data;
        reply_ok(at_data.data_type);
        GAP_SetParamValue(TGAP_GEN_DISC_SCAN, at_data.sacn_time*1000);
        GAP_SetParamValue(TGAP_LIM_DISC_SCAN, at_data.sacn_time*1000);
        osal_stop_timerEx(simpleBLETaskId,MASTER_CONN_TIMEOUT_EVT);
        osal_stop_timerEx(simpleBLETaskId,START_MASTER_CONN_EVT);
        GAPMultiRole_TerminateConnection(GAP_CONNHANDLE_INIT);
        ble_task_set(USER_TASK_START, START_SCAN_EVT, NULL);//发起一次扫描
        
    }
    else if(temp_data == 0)
    {
        LOG("Cancel at scan!\n");
        at_data.sacn_time = temp_data;
        reply_ok(at_data.data_type);
        GAPMultiRole_CancelDiscovery();
    }

 
}

//取消扫描
void at_cancel_scanen(uint8_t *data,uint8_t len)
{
    uint8_t temp_mode = ble_get_at_mode();
    
    if(temp_mode == BLE_ONLY_SLAVE)//单从机下不允许操作
    {
        return ;
    }
    reply_ok(at_data.data_type);
    GAPMultiRole_CancelDiscovery();
}

//获取link命令参数类型：link命令参数有两种，一种是扫描时候的序号，一种是mac地址
uint8_t get_at_link_data_type(uint8_t *data,uint8_t len)
{
    for(int i = 0 ; i < len ; i ++)
    {
        if((*(data + i) == ':')&&(*(data + i +1) == '<'))
        {
            for(int j = 1 ; j < len - i ; j ++)
            {
                if(*(data + i + j) == '>')
                {
                    return j-2;
                }
                else if(j == len -i - 1)//找完了还没找到>,非法
                {
                    return AT_CMD_ERROR;
                }
            }
        }
        else if(i == (len - 1))//找完了还没找到数据，非法，link命令没有查询动作
        {
            return AT_CMD_ERROR;
        }
    }
    return AT_CMD_ERROR;
}

//获取AT命令中的数据
uint8_t get_at_link_data(uint8_t *data, uint8_t len, uint8_t data_type, uint8_t *mac)
{
    uint8_t temp_mac[12];
    uint8_t temp_data = 0;
    LOG("data_type %d\n",data_type);
    //这里即允许1又允许2是为了优化体验,1和2代表位数 比如3 和03是一个意思
    if((data_type == 1)||(data_type == 2))//收到的是NO号（序号）
    { 
        for(int i = 0 ; i < len ; i ++)
        {    
            if((*(data + i) == ':')&&(*(data + i + 1) == '<'))
            {
                if((*(data + i + 3) == '>')&&(*(data + i + 2) >= '0')&&(*(data + i + 2) <= '9'))//个位数
                {
                    temp_data = *(data + i + 2) - 0x30;
                    break;
                }
                else if((*(data + i + 4) == '>')&&(*(data + i + 2) >= '0')&&(*(data + i + 2) <= '9')
                &&(*(data + i + 3) >= '0')&&(*(data + i + 3) <= '9'))//十位数
                {
                    temp_data = (*(data + i + 2) - 0x30)*10+(*(data + i + 3) - 0x30);
                    break;
                }
                else
                {
                    return AT_CMD_ERROR;
                }
            }
            else if(i == (len - 1))//找完了还没找到数据，非法，link命令没有查询动作
            {
                return AT_CMD_ERROR;
            }
        }
        if(temp_data >= DEFAULT_MAX_SCAN_RES)
        {
            return AT_CMD_ERROR;
        }
        if((scanDataAddr[temp_data][0] == 0x00)&&(scanDataAddr[temp_data][1] == 0x00)&&(scanDataAddr[temp_data][2] == 0x00)\
        &&(scanDataAddr[temp_data][3] == 0x00)&&(scanDataAddr[temp_data][4] == 0x00)&&(scanDataAddr[temp_data][5] == 0x00))
        {
            return AT_CMD_ERROR;
        }
        osal_memcpy(mac,&scanDataAddr[temp_data][0],6);
        
    }
    else if(data_type == 12)//收到的是mac地址
    {
        for(int i = 0 ; i < len ; i ++)
        {
            if((*(data + i) == ':')&&(*(data + i + 1) == '<'))
            {
                if(*(data + i + 14) != '>')//非法
                {
                    return AT_CMD_ERROR;
                }

                for(int j = 0 ; j < 12 ; j ++)
                {
                    temp_mac[j] = *(data + i + j +2 ) ;
                }
                break;
            }
            else if(i == (len - 1))//找完了还没找到数据，非法，link命令没有查询动作
            {
                LOG("LINK ERROR !\n");
                return AT_CMD_ERROR;
            }
        }

        for(char i=0; i<12; i++)
        {
            if( (temp_mac[i] >= '0') && (temp_mac[i] <= '9') )
            {
                mac[5-(i>>1)] |= (temp_mac[i]-'0')<<((i%2)?0:4);
            }
            else if( (temp_mac[i] >= 'A') && (temp_mac[i] <= 'F') )
            {
                mac[5-(i>>1)] |= (temp_mac[i]-'A'+0x0A)<<((i%2)?0:4);
            }
            else if( (temp_mac[i] >= 'a') && (temp_mac[i] <= 'f') )
            {
                mac[5-(i>>1)] |= (temp_mac[i]-'a'+0x0A)<<((i%2)?0:4);
            }
            else
            {
                break;
            }
        }
    }
    else
    {
        return AT_CMD_ERROR;
    }
    return AT_CMD_SUCCES;
}

//写白名单
void at_white_list_enable(uint8_t channel,uint8_t enable)
{
    uint8_t temp_null_mac[B_ADDR_LEN] = {0};
    if(enable == 1)
    {
        LOG("2 NULL\n");
        slaveDevInfo[channel].AutoConnection = 1;
        HCI_LE_AddWhiteListCmd(LL_WHITELIST_DEV_TYPE_SLAVE, LL_DEV_ADDR_TYPE_PUBLIC,slaveDevInfo[channel].PeerAddr);//将mac地址加入白名单
        ble_task_set(USER_TASK_START, START_MASTER_CONN_EVT, NULL);
        user_data.autolink |= (1<<channel);
        osal_memcpy(&user_data.autolinkaddr[channel][0],slaveDevInfo[channel].PeerAddr,B_ADDR_LEN);
        
        
    }
    else if(enable == 0)
    {
        LOG("3 NULL channel %d\n",channel);
        slaveDevInfo[channel].AutoConnection = 0;
        HCI_LE_RemoveWhiteListCmd(LL_WHITELIST_DEV_TYPE_SLAVE,LL_DEV_ADDR_TYPE_PUBLIC,slaveDevInfo[channel].PeerAddr);//将mac地址从白名单删除
        user_data.autolink &= ~ (1<<channel);   
        osal_memcpy(&user_data.autolinkaddr[channel][0],temp_null_mac,B_ADDR_LEN);
    }
    user_data_save();
}

//link命令处理
void at_link(uint8_t *data,uint8_t len)
{
    uint8_t temp_channel;
    uint8_t temp_mac[6] = {0};
    uint8_t temp_data_type = 0;
    uint8_t temp_mode = ble_get_at_mode();
    temp_data_type = get_at_link_data_type(data,len);

    uint8_t ret = get_at_link_data(data, len, temp_data_type,temp_mac);
    if( ret != AT_CMD_SUCCES)//不成功不处理
    {
        return ;
    }

    if(temp_mode == BLE_ONLY_SLAVE)//从机模式不允许连接其他设备
    {
        return;
    }
    LOG_DUMP_BYTE(temp_mac,6);

    temp_channel = writeConnectIndexByAddr(temp_mac);//将man地址写入全局变量保存
    LOG("temp_channel %d\n",temp_channel);
    if(slaveDevInfo[temp_channel].ConnectionHandle != 0xFF)
    {
        return;
    }
    ble_link_dev(temp_mac);
    //at_white_list_enable(temp_channel,1);
    //ble_task_set(USER_TASK_START, START_MASTER_CONN_EVT, NULL);
    temp_channel += 0x30;
    reply_at_data("LINK:",5,&temp_channel,1);

}
//获取设备状态
void at_getstat(uint8_t *data,uint8_t len)
{
    uint8_t temp_mode = ble_get_at_mode();
    uint8_t temp_devstat[23+MAX_CONNECTION_NUM]= {0};
    uint8_t temp_devstat_len = 0;
    uint8_t temp_only_slave_link_stat = 0;
    LOG("at_getstat \n");
    if(temp_mode == BLE_ONLY_SLAVE)
    {
        temp_only_slave_link_stat = ble_get_master_link_num() + 0x30;
        reply_at_data("GETSTAT:",6,&temp_only_slave_link_stat,1);
    }
    else if(temp_mode == BLE_ONLY_MASTER)
    {
        temp_devstat[temp_devstat_len++] = 'G';
        temp_devstat[temp_devstat_len++] = 'E';
        temp_devstat[temp_devstat_len++] = 'T';
        temp_devstat[temp_devstat_len++] = 'S';
        temp_devstat[temp_devstat_len++] = 'T';
        temp_devstat[temp_devstat_len++] = 'A';
        temp_devstat[temp_devstat_len++] = 'T';
        temp_devstat[temp_devstat_len++] = ':';
        temp_devstat[temp_devstat_len++] = '<';
        temp_devstat[temp_devstat_len++] = 'S';
        for(int i = 0 ; i < g_slaveMaxNum ; i++)
        {
            temp_devstat[temp_devstat_len++] = slaveDevInfo[i].ConnectionState + 0x30;
        }
        temp_devstat[temp_devstat_len++] = '>';
        temp_devstat[temp_devstat_len++] = '\r';
        temp_devstat[temp_devstat_len++] = '\n';

        //while(HalUartGetTxReady(UART1) == ERR_BUSY);
        //HalUartSendBuf(UART1, temp_devstat, temp_devstat_len);
        at_send_data(at_data.data_type,temp_devstat,temp_devstat_len);
    }
    else if(temp_mode == BLE_MASTER_AND_SLAVE)
    {
        temp_devstat[temp_devstat_len++] = 'G';
        temp_devstat[temp_devstat_len++] = 'E';
        temp_devstat[temp_devstat_len++] = 'T';
        temp_devstat[temp_devstat_len++] = 'S';
        temp_devstat[temp_devstat_len++] = 'T';
        temp_devstat[temp_devstat_len++] = 'A';
        temp_devstat[temp_devstat_len++] = 'T';
        temp_devstat[temp_devstat_len++] = ':';
        temp_devstat[temp_devstat_len++] = '<';
        temp_devstat[temp_devstat_len++] = 'M';
        for(int i = 0 ; i < g_masterMaxNum ; i++)
        {
            temp_devstat[temp_devstat_len++] = masterDevInfo[i].ConnectionState + 0x30;
        }
        temp_devstat[temp_devstat_len++] = 'S';
        for(int i = 0 ; i < g_slaveMaxNum ; i++)
        {
            temp_devstat[temp_devstat_len++] = slaveDevInfo[i].ConnectionState + 0x30;
        }
        temp_devstat[temp_devstat_len++] = '>';
        temp_devstat[temp_devstat_len++] = '\r';
        temp_devstat[temp_devstat_len++] = '\n';
        
        //while(HalUartGetTxReady(UART1) == ERR_BUSY);
        //HalUartSendBuf(UART1, temp_devstat, temp_devstat_len);
        at_send_data(at_data.data_type,temp_devstat,temp_devstat_len);
    }
 
}

uint8_t at_get_disc_data(uint8_t *data,uint8_t len,uint8_t *role, uint8_t *channel)
{

    for(int i = 0 ; i < len ; i ++)
    {
        if(*(data+i) == '<')//找到'<'
        {
            *role = *(data+i+1);
            *channel = *(data+i+5);

            if((*(data+i+2) != '>')&&(*(data+i+6) != '>'))
            {
                return AT_CMD_ERROR;
            } 

            if((*channel < '0')||(*channel > '7'))//通道号为0-7
            {

                return AT_CMD_ERROR;
            }

            if((*role != 'M')&&(*role != 'S'))
            {
                return AT_CMD_ERROR;
            }
            break;
        }
        else if(i == len-1)
        {

            return AT_CMD_FIND;
        }
    }
    return AT_CMD_SUCCES;
}
//断开连接命令
void at_disc(uint8_t *data,uint8_t len)
{
    uint8_t temp_role = 0;
    uint8_t temp_channel = 0;
    
    //get_at_data_Nbyte(data,len,temp_data,12);
    uint8_t ret = at_get_disc_data(data, len, &temp_role, &temp_channel);
    LOG("disc ret %d role %c channel %d\n",ret,temp_role,temp_channel);
    uint8_t temp_mode = ble_get_at_mode();
    if((temp_mode == BLE_ONLY_SLAVE)&&(temp_role == 'S'))//从机模式下不允许操作从机断开
    {
        return;
    }

    if((temp_mode == BLE_ONLY_SLAVE)&&(temp_role == 'M')&&(temp_channel == 1))//从机模式下不允许操作主机1断开
    {
        return;
    }

    if(ret == AT_CMD_ERROR)
    {
        return ;
    }
    else if(ret == AT_CMD_FIND)//不输出参数就断开所有设备
    {
        reply_ok(at_data.data_type);
        //osal_stop_timerEx(simpleBLETaskId,MASTER_CONN_TIMEOUT_EVT);
        //osal_stop_timerEx(simpleBLETaskId,START_MASTER_CONN_EVT);

        for(int i = 0 ; i < g_slaveMaxNum; i++)
        {
            //HCI_LE_RemoveWhiteListCmd(LL_WHITELIST_DEV_TYPE_SLAVE,LL_DEV_ADDR_TYPE_PUBLIC,slaveDevInfo[i].PeerAddr);
            //slaveDevInfo[i].AutoConnection = 0;
            at_white_list_enable(i, 0);
        }
        GAPMultiRole_TerminateConnection(GAP_CONNHANDLE_INIT);
        GAPMultiRole_TerminateConnection(GAP_CONNHANDLE_ALL);
        LOG("DISC ALL\n");
    }
    else 
    {
        
        temp_channel -= 0x30;
        
        if(temp_role == 'M')//masterDevInfo
        {
            if(temp_channel < g_masterMaxNum )
            {
                LOG("DISC M %d\n",temp_channel);
                GAPMultiRole_TerminateConnection(masterDevInfo[temp_channel].ConnectionHandle);
                reply_ok(at_data.data_type);
            }
        }
        else if(temp_role == 'S')//slaveDevInfo
        {
            if(temp_channel < g_slaveMaxNum )
            {
                LOG("DISC S %d\n",temp_channel);
                //HCI_LE_RemoveWhiteListCmd(LL_WHITELIST_DEV_TYPE_SLAVE,LL_DEV_ADDR_TYPE_PUBLIC,slaveDevInfo[temp_channel].PeerAddr);
                at_white_list_enable(temp_channel, 0);
                GAPMultiRole_TerminateConnection(slaveDevInfo[temp_channel].ConnectionHandle);
                reply_ok(at_data.data_type);
                //slaveDevInfo[temp_channel].AutoConnection = 1;
            }
        }
    }
}
//查询连接设备信息
void at_connlist(uint8_t *data,uint8_t len)
{
    int8 rssi = 0;
    uint8_t temp_conlist[35];
    uint8_t temp_conlist_len = 0;
    char hex[] = "0123456789ABCDEF";
    reply_ok(at_data.data_type);

    for(int i = 0 ; i < ble_get_master_num() ; i++)
    {
        if(masterDevInfo[i].ConnectionHandle != 0xff)
        {
            LL_ReadRssi(masterDevInfo[i].ConnectionHandle, &rssi);
            temp_conlist[temp_conlist_len++] = '<';
            temp_conlist[temp_conlist_len++] = 'M';
            temp_conlist[temp_conlist_len++] = '>';
            temp_conlist[temp_conlist_len++] = '<';
            temp_conlist[temp_conlist_len++] = i + 0x30;
            temp_conlist[temp_conlist_len++] = '>';
            temp_conlist[temp_conlist_len++] = ',';
            temp_conlist[temp_conlist_len++] = '<';
            temp_conlist[temp_conlist_len++] = hex[masterDevInfo[i].PeerAddr[5] >> 4];
            temp_conlist[temp_conlist_len++] = hex[masterDevInfo[i].PeerAddr[5] & 0x0F];
            temp_conlist[temp_conlist_len++] = hex[masterDevInfo[i].PeerAddr[4] >> 4];
            temp_conlist[temp_conlist_len++] = hex[masterDevInfo[i].PeerAddr[4] & 0x0F];
            temp_conlist[temp_conlist_len++] = hex[masterDevInfo[i].PeerAddr[3] >> 4];
            temp_conlist[temp_conlist_len++] = hex[masterDevInfo[i].PeerAddr[3] & 0x0F];
            temp_conlist[temp_conlist_len++] = hex[masterDevInfo[i].PeerAddr[2] >> 4];
            temp_conlist[temp_conlist_len++] = hex[masterDevInfo[i].PeerAddr[2] & 0x0F];
            temp_conlist[temp_conlist_len++] = hex[masterDevInfo[i].PeerAddr[1] >> 4];
            temp_conlist[temp_conlist_len++] = hex[masterDevInfo[i].PeerAddr[1] & 0x0F];
            temp_conlist[temp_conlist_len++] = hex[masterDevInfo[i].PeerAddr[0] >> 4];
            temp_conlist[temp_conlist_len++] = hex[masterDevInfo[i].PeerAddr[0] & 0x0F];
            temp_conlist[temp_conlist_len++] = '>';
            temp_conlist[temp_conlist_len++] = ',';
            temp_conlist[temp_conlist_len++] = '<';
            temp_conlist[temp_conlist_len++] = '-';
            temp_conlist[temp_conlist_len++] = (ABS(rssi)/ 10 % 10) + 0x30;
            temp_conlist[temp_conlist_len++] = (ABS(rssi)/ 1 % 10) + 0x30;
            temp_conlist[temp_conlist_len++] = '>';
            temp_conlist[temp_conlist_len++] = '\r';
            temp_conlist[temp_conlist_len++] = '\n';
            //while(HalUartGetTxReady(UART1) == ERR_BUSY);
            //HalUartSendBuf(UART1, temp_conlist, temp_conlist_len);
            at_send_data(at_data.data_type,temp_conlist,temp_conlist_len);
            temp_conlist_len = 0;
        }

    }
    for(int i = 0 ; i < ble_get_slave_num() ; i++)
    {
        if(slaveDevInfo[i].ConnectionHandle != 0xff)
        {
            
            LL_ReadRssi(slaveDevInfo[i].ConnectionHandle, &rssi);
            temp_conlist[temp_conlist_len++] = '<';
            temp_conlist[temp_conlist_len++] = 'S';
            temp_conlist[temp_conlist_len++] = '>';
            temp_conlist[temp_conlist_len++] = '<';
            temp_conlist[temp_conlist_len++] = i + 0x30;
            temp_conlist[temp_conlist_len++] = '>';
            temp_conlist[temp_conlist_len++] = ',';
            temp_conlist[temp_conlist_len++] = '<';
            temp_conlist[temp_conlist_len++] = hex[slaveDevInfo[i].PeerAddr[5] >> 4];
            temp_conlist[temp_conlist_len++] = hex[slaveDevInfo[i].PeerAddr[5] & 0x0F];
            temp_conlist[temp_conlist_len++] = hex[slaveDevInfo[i].PeerAddr[4] >> 4];
            temp_conlist[temp_conlist_len++] = hex[slaveDevInfo[i].PeerAddr[4] & 0x0F];
            temp_conlist[temp_conlist_len++] = hex[slaveDevInfo[i].PeerAddr[3] >> 4];
            temp_conlist[temp_conlist_len++] = hex[slaveDevInfo[i].PeerAddr[3] & 0x0F];
            temp_conlist[temp_conlist_len++] = hex[slaveDevInfo[i].PeerAddr[2] >> 4];
            temp_conlist[temp_conlist_len++] = hex[slaveDevInfo[i].PeerAddr[2] & 0x0F];
            temp_conlist[temp_conlist_len++] = hex[slaveDevInfo[i].PeerAddr[1] >> 4];
            temp_conlist[temp_conlist_len++] = hex[slaveDevInfo[i].PeerAddr[1] & 0x0F];
            temp_conlist[temp_conlist_len++] = hex[slaveDevInfo[i].PeerAddr[0] >> 4];
            temp_conlist[temp_conlist_len++] = hex[slaveDevInfo[i].PeerAddr[0] & 0x0F];
            temp_conlist[temp_conlist_len++] = '>';
            temp_conlist[temp_conlist_len++] = ',';
            temp_conlist[temp_conlist_len++] = '<';
            temp_conlist[temp_conlist_len++] = '-';
            temp_conlist[temp_conlist_len++] = (ABS(rssi)/ 10 % 10) + 0x30;
            temp_conlist[temp_conlist_len++] = (ABS(rssi)/ 1 % 10) + 0x30;
            temp_conlist[temp_conlist_len++] = '>';
            temp_conlist[temp_conlist_len++] = '\r';
            temp_conlist[temp_conlist_len++] = '\n';

            //while(HalUartGetTxReady(UART1) == ERR_BUSY);
            //HalUartSendBuf(UART1, temp_conlist, temp_conlist_len);
            at_send_data(at_data.data_type,temp_conlist,temp_conlist_len);
            temp_conlist_len = 0;
        }

    }
    uint8_t conneNum = GAP_NumActiveConnections();
    if(conneNum >= 10)
    {
        uint8_t temp_conneNum[2]={0};
        temp_conneNum[0] = (conneNum / 10 % 10) +0x30;
        temp_conneNum[1] = (conneNum / 1  % 10) +0x30;
        reply_at_data("CONLIST:", 8, temp_conneNum, 2);
    }
    else
    {
        conneNum += 0x30;
        reply_at_data("CONLIST:", 8, &conneNum, 1);
    }
    
    
    
}

uint8_t at_get_name_data(uint8_t *data, uint8_t len, uint8_t *name ,uint8_t *name_len)
{
    uint8_t temp_name_len = 0;
    for(int i = 0 ; i < len ; i ++)
    {
        if((*(data + i) == ':')&&(*(data + i + 1) == '<'))
        {
            for(int j = 1 ; j < len - i; j++)
            {
                
                //if((*(data + i + j + 1) == '>')&&(*(data + i + j + 2) == '\r')&&(*(data + i + j + 3) == '\n'))
                if(*(data + i + j + 1) == '>')
                {
                    *name_len = temp_name_len;
                    return AT_CMD_SUCCES;
                }
                *(name+j-1) = *(data + i + j + 1);

                temp_name_len++;
                if( temp_name_len > 18 )//设置名字过长非法
                {
                    return AT_CMD_ERROR;
                }
            }
        }
        else if(i == len - 1)//没找到参数，表示查询
        {
            return AT_CMD_FIND;
        }
    }
    
    return AT_CMD_SUCCES;
}

void at_name(uint8_t *data,uint8_t len)
{
    uint8_t temp_name[18];
    uint8_t temp_name_len = 0 ;
    uint8_t ret = 0 ;

    ret = at_get_name_data(data,len,temp_name,&temp_name_len);

    if((ret == AT_CMD_ERROR)||(temp_name_len > 18))
    {
        LOG("set name error \n");
        return ;
    }
    
    if(ret == AT_CMD_FIND)
    {
        reply_at_data("NAME:", 5,  user_data.name, osal_strlen((char *) user_data.name));
    }
    else 
    {
        LOG("name:%s\r\n", user_data.name);
        LOG("temp_name:%s\r\n", temp_name);
        LOG("temp_name_len:%d\r\n", temp_name_len);
        reply_ok(at_data.data_type);
        ble_set_adv_enable(FALSE);

        osal_memset(user_data.name, 0, sizeof(user_data.name));
        osal_memcpy(user_data.name, temp_name, temp_name_len);
        
        ble_set_adv_enable(TRUE);
        user_data_save();
    }
}
//设置扫描过滤广播名
void at_setfile(uint8_t *data,uint8_t len)
{
    uint8_t ret = 0;
    uint8_t temp_name[18];
    uint8_t temp_name_len = 0 ;

    ret = at_get_name_data(data,len,temp_name,&temp_name_len);

    if((ret == AT_CMD_ERROR)||(temp_name_len > 18))
    {
        LOG("set file name error \n");
        return ;
    }

    if(ret == AT_CMD_FIND)
    {
        if( osal_strlen((char *)at_data.file_name) == 0)
        {
            uint8_t null_str[4] = "NULL";
            reply_at_data("SETFILT:", 8, null_str, 4);
        }
        else
        {
            reply_at_data("SETFILT:", 8, at_data.file_name, osal_strlen((char *)at_data.file_name));
        }
        
    }
    else 
    {
        //osal_memcpy(at_data.file_name, temp_name, temp_name_len);
        osal_memset(at_data.file_name, 0, sizeof(at_data.file_name));
        osal_memcpy(at_data.file_name, temp_name, temp_name_len);
        LOG("name:%s\r\n", at_data.file_name);
        set_broadcast_name_filt(temp_name_len,at_data.file_name);
        reply_ok(at_data.data_type);
    }
}

//设置扫描过滤广播名
void at_clrfile(uint8_t *data,uint8_t len)
{
    clear_broadcast_name_filt();
    //LOG("sizeof(at_data.file_name) %d\n",sizeof(at_data.file_name));
    osal_memset(at_data.file_name, 0, sizeof(at_data.file_name));
    reply_ok(at_data.data_type);
}
//恢复出厂设置
void at_restore(uint8_t *data,uint8_t len)
{
    reply_ok(at_data.data_type);
    HalFlashErase(BAUD_FLASH_ADDR1>>12);
    HalFlashErase(BAUD_FLASH_ADDR2>>12);
    GAPMultiRole_TerminateConnection(GAP_CONNHANDLE_ALL);
    NVIC_SystemReset();
}

//进入OTA
void at_ota(uint8_t *data,uint8_t len)
{
    reply_ok(at_data.data_type);
    LOG("reboot to dul ota.\r\n");
    write_reg(0x1FFF18FC,0x55AAAA55);
    GAPMultiRole_TerminateConnection(GAP_CONNHANDLE_INIT);
    GAPMultiRole_TerminateConnection(GAP_CONNHANDLE_ALL);
    WaitMs(500);
    NVIC_SystemReset();
}

//进入sleep
void at_sleep(uint8_t *data,uint8_t len)
{
    reply_ok(at_data.data_type);
    pwroff_cfg_t cfg;

    cfg.pin = WAKEUP_PIN;
    cfg.type = POL_FALLING;
    cfg.on_time = 100;
    
    hal_pwrmgr_poweroff(&cfg, 1);
}

void at_linkdata(uint8_t *data,uint8_t len)
{
    //LOG("slaveDevInfo:\n");
    //for(int i = 0 ; i < g_slaveMaxNum ; i ++)
    {
      //  LOG("channel :%d hld 0x%02d\n",i,slaveDevInfo[i].ConnectionHandle);
     //   LOG_DUMP_BYTE(slaveDevInfo[i].PeerAddr,6);
    }
    LOG("-OK\n");
    reply_ok(at_data.data_type);
}

void at_constat(void)
{
    uint8_t temp_mode = ble_get_at_mode();
    uint8_t temp_devstat[25+MAX_CONNECTION_NUM]= {0};
    uint8_t temp_devstat_len = 0;
    uint8_t temp_only_slave_link_stat = 0;
    //LOG("at_constat is work\n");
    if(temp_mode == BLE_ONLY_SLAVE)
    {
        temp_only_slave_link_stat = ble_get_master_link_num() + 0x30;
        reply_at_data("GETSTAT:",6,&temp_only_slave_link_stat,1);
    }
    else if(temp_mode == BLE_ONLY_MASTER)
    {
        temp_devstat[temp_devstat_len++] = 'A';
        temp_devstat[temp_devstat_len++] = 'T';
        temp_devstat[temp_devstat_len++] = '+';
        temp_devstat[temp_devstat_len++] = 'C';
        temp_devstat[temp_devstat_len++] = 'O';
        temp_devstat[temp_devstat_len++] = 'N';
        temp_devstat[temp_devstat_len++] = 'S';
        temp_devstat[temp_devstat_len++] = 'T';
        temp_devstat[temp_devstat_len++] = 'A';
        temp_devstat[temp_devstat_len++] = 'T';
        temp_devstat[temp_devstat_len++] = ':';
        temp_devstat[temp_devstat_len++] = '<';
        temp_devstat[temp_devstat_len++] = 'S';
        for(int i = 0 ; i < g_slaveMaxNum ; i++)
        {
            temp_devstat[temp_devstat_len++] = slaveDevInfo[i].ConnectionState + 0x30;
        }
        temp_devstat[temp_devstat_len++] = '>';
        temp_devstat[temp_devstat_len++] = '\r';
        temp_devstat[temp_devstat_len++] = '\n';

        //while(HalUartGetTxReady(UART1) == ERR_BUSY);
        //HalUartSendBuf(UART1, temp_devstat, temp_devstat_len);
        at_send_data(at_data.data_type,temp_devstat,temp_devstat_len);
        temp_devstat_len = 0;
    }
    else if(temp_mode == BLE_MASTER_AND_SLAVE)
    {
        temp_devstat[temp_devstat_len++] = 'A';
        temp_devstat[temp_devstat_len++] = 'T';
        temp_devstat[temp_devstat_len++] = '+';
        temp_devstat[temp_devstat_len++] = 'C';
        temp_devstat[temp_devstat_len++] = 'O';
        temp_devstat[temp_devstat_len++] = 'N';
        temp_devstat[temp_devstat_len++] = 'S';
        temp_devstat[temp_devstat_len++] = 'T';
        temp_devstat[temp_devstat_len++] = 'A';
        temp_devstat[temp_devstat_len++] = 'T';
        temp_devstat[temp_devstat_len++] = ':';
        temp_devstat[temp_devstat_len++] = '<';
        temp_devstat[temp_devstat_len++] = 'M';
        for(int i = 0 ; i < g_masterMaxNum ; i++)
        {
            temp_devstat[temp_devstat_len++] = masterDevInfo[i].ConnectionState + 0x30;
        }
        temp_devstat[temp_devstat_len++] = 'S';
        for(int i = 0 ; i < g_slaveMaxNum ; i++)
        {
            temp_devstat[temp_devstat_len++] = slaveDevInfo[i].ConnectionState + 0x30;
        }
        temp_devstat[temp_devstat_len++] = '>';
        temp_devstat[temp_devstat_len++] = '\r';
        temp_devstat[temp_devstat_len++] = '\n';
        
        //while(HalUartGetTxReady(UART1) == ERR_BUSY);
        //HalUartSendBuf(UART1, temp_devstat, temp_devstat_len);
        at_send_data(at_data.data_type,temp_devstat,temp_devstat_len);
        temp_devstat_len = 0;
    }
}

void at_rxhandle(uint8_t role ,uint8_t rxhandle)
{
    uint8_t temp_rxhandle[25];
    uint8_t temp_rxhandle_len = 0;
    //LOG("at_rxhandle is work\n");
    if(rxhandle == 0xff)//非法
    {
        return;
    }
    temp_rxhandle[temp_rxhandle_len++] = 'A';
    temp_rxhandle[temp_rxhandle_len++] = 'T';
    temp_rxhandle[temp_rxhandle_len++] = '+';
    temp_rxhandle[temp_rxhandle_len++] = 'R';
    temp_rxhandle[temp_rxhandle_len++] = 'X';
    temp_rxhandle[temp_rxhandle_len++] = 'H';
    temp_rxhandle[temp_rxhandle_len++] = 'A';
    temp_rxhandle[temp_rxhandle_len++] = 'N';
    temp_rxhandle[temp_rxhandle_len++] = 'D';
    temp_rxhandle[temp_rxhandle_len++] = 'L';
    temp_rxhandle[temp_rxhandle_len++] = 'E';
    temp_rxhandle[temp_rxhandle_len++] = ':';
    temp_rxhandle[temp_rxhandle_len++] = '<';
    if(role == AT_MASTER)
    {
        temp_rxhandle[temp_rxhandle_len++] = 'M';
    }
    else if(role == AT_SLAVE)
    {
        temp_rxhandle[temp_rxhandle_len++] = 'S';
    }
    temp_rxhandle[temp_rxhandle_len++] = '>';
    temp_rxhandle[temp_rxhandle_len++] = ',';
    temp_rxhandle[temp_rxhandle_len++] = '<';
    temp_rxhandle[temp_rxhandle_len++] = (rxhandle/ 10 % 10) + 0x30;
    temp_rxhandle[temp_rxhandle_len++] = (rxhandle/ 1 % 10) + 0x30;
    temp_rxhandle[temp_rxhandle_len++] = '>';
    temp_rxhandle[temp_rxhandle_len++] = '\r';
    temp_rxhandle[temp_rxhandle_len++] = '\n';

    //while(HalUartGetTxReady(UART1) == ERR_BUSY);
    //HalUartSendBuf(UART1, temp_rxhandle, temp_rxhandle_len);
    at_send_data(at_data.data_type,temp_rxhandle,temp_rxhandle_len);
    temp_rxhandle_len = 0;

}
uint8_t at_get_autolinkcfg_data(uint8_t *data,uint8_t len, uint8_t *win, uint8_t *inter)
{
    uint8_t temp_num = 0;
    for(int i = 0 ; i < len ; i ++)//查找参数个数
    {
        if(*(data + i) == '<')
        {
            temp_num ++;
            switch(temp_num)
            {
                case 1:
                    *win = str_to_hex(*(data + i + 1));
                    if(*(data + i + 2) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                    break;
                case 2:
                    *inter = str_to_hex(*(data + i + 1));
                    if(*(data + i + 2) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                    break;
            }
        }
        else if((i == len - 1)&&(temp_num == 0))//没找到参数，表示查询
        {
            return AT_CMD_FIND;
        }
    }
    return temp_num;
}

void at_autolinkcfg(uint8_t *data,uint8_t len)
{
    uint8_t ret = 0;
    uint8_t temp_win = 0;
    uint8_t temp_inter = 0;
    uint8_t temp_mode = ble_get_at_mode();
    uint8_t temp_cfg[22];
    uint8_t temp_cfg_len = 0;
    ret = at_get_autolinkcfg_data(data,len,&temp_win,&temp_inter);

    if(ret == AT_CMD_ERROR)
    {
        LOG("at_autolinkcfg error!\n");
        return;
    }

    if((temp_win > 4)||(temp_inter > 9))
    {
        LOG("at_autolinkcfg error!!\n");
        return;
    }

    if(temp_mode == BLE_ONLY_SLAVE)
    {
        return;
    }
    if(ret == AT_CMD_FIND)
    {
        temp_cfg[temp_cfg_len++] = 'A';
        temp_cfg[temp_cfg_len++] = 'U';
        temp_cfg[temp_cfg_len++] = 'T';
        temp_cfg[temp_cfg_len++] = 'O';
        temp_cfg[temp_cfg_len++] = 'L';
        temp_cfg[temp_cfg_len++] = 'N';
        temp_cfg[temp_cfg_len++] = 'K';
        temp_cfg[temp_cfg_len++] = 'C';
        temp_cfg[temp_cfg_len++] = 'F';
        temp_cfg[temp_cfg_len++] = 'G';
        temp_cfg[temp_cfg_len++] = ':';
        temp_cfg[temp_cfg_len++] = '<';
        temp_cfg[temp_cfg_len++] = user_data.scan_window + 0x30;
        temp_cfg[temp_cfg_len++] = '>';
        temp_cfg[temp_cfg_len++] = ',';
        temp_cfg[temp_cfg_len++] = '<';
        temp_cfg[temp_cfg_len++] = user_data.scan_interval + 0x30;
        temp_cfg[temp_cfg_len++] = '>';
        temp_cfg[temp_cfg_len++] = '\r';
        temp_cfg[temp_cfg_len++] = '\n';

        at_send_data(at_data.data_type,temp_cfg,temp_cfg_len);
        temp_cfg_len = 0;
    }
    else
    {
        user_data.scan_interval = temp_inter;
        user_data.scan_window = temp_win;
            // Set scan duration parameter

        reply_ok(at_data.data_type);
        user_data_save();
    }

    LOG("at_autolinkcfg \n");
    
}
uint8_t at_get_autolink_data(uint8_t *data,uint8_t len, uint8_t *handle, uint8_t *enable ,uint8_t *mac)
{
    uint8_t temp_num = 0;
    for(int i = 0 ; i < len ; i ++)//查找参数个数
    {
        if(*(data + i) == '<')
        {
            temp_num ++;
            switch(temp_num)
            {
                case 1:
                    *handle = str_to_hex(*(data + i + 1));
                    if(*(data + i + 2) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                    break;
                case 2:
                    *enable = str_to_hex(*(data + i + 1));
                    if(*(data + i + 2) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                    break;
                case 3:
                    for(int j = 0 ; j <6 ; j++)//基础UUID长度为128bit=16字节
                    {
                        mac[5-j] = ((str_to_hex(*(data + i + 2*j+1))<<4)|(str_to_hex(*(data + i + 2*j+2))&0x0F));
                    }
                    if(*(data + i + 13) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                    break;
            }
        }
        else if((i == len - 1)&&(temp_num == 0))//没找到参数，表示查询
        {
            
            return AT_CMD_FIND;
        }
    }


    return temp_num;
}

void at_autolink(uint8_t *data,uint8_t len)
{
    uint8_t temp_channel = 0;
    uint8_t temp_enable = 0;
    uint8_t temp_mac[6] = {0};
    uint8_t temp_mac_null[6] = {0};
    uint8_t temp_data = 0;
    char hex[] = "0123456789ABCDEF";
    temp_data = at_get_autolink_data(data,len,&temp_channel,&temp_enable,temp_mac);
    LOG("temp_data %d channel %d enable %d\n",temp_data,temp_channel,temp_enable);
    LOG("mac:");
    LOG_DUMP_BYTE(temp_mac, 6);
    if((temp_data == AT_CMD_ERROR)||(temp_enable != 0)&&(temp_enable != 1)||(temp_channel >7))
    {
        LOG("at_autolink error!\n");
        return;
    }
    uint8_t temp_mode = ble_get_at_mode();
    if(temp_mode == BLE_ONLY_SLAVE)
    {
        return;
    }

    if(temp_data == AT_CMD_FIND)
    {
        uint8_t temp_autolink[30];
        uint8_t temp_autolink_len = 0;
        uint8_t conneNum = 0;
        LOG("find\n");
        reply_ok(at_data.data_type);
        for(int i = 0 ; i < g_slaveMaxNum ; i++)
        {
            temp_autolink[temp_autolink_len++] = '<';
            temp_autolink[temp_autolink_len++] = i + 0x30;
            temp_autolink[temp_autolink_len++] = '>';
            temp_autolink[temp_autolink_len++] = ',';
            temp_autolink[temp_autolink_len++] = '<';
            temp_autolink[temp_autolink_len++] = slaveDevInfo[i].AutoConnection + 0x30;
            temp_autolink[temp_autolink_len++] = '>';
            temp_autolink[temp_autolink_len++] = ',';
            temp_autolink[temp_autolink_len++] = '<';
            temp_autolink[temp_autolink_len++] = hex[slaveDevInfo[i].PeerAddr[5] >> 4];
            temp_autolink[temp_autolink_len++] = hex[slaveDevInfo[i].PeerAddr[5] & 0x0F];
            temp_autolink[temp_autolink_len++] = hex[slaveDevInfo[i].PeerAddr[4] >> 4];
            temp_autolink[temp_autolink_len++] = hex[slaveDevInfo[i].PeerAddr[4] & 0x0F];
            temp_autolink[temp_autolink_len++] = hex[slaveDevInfo[i].PeerAddr[3] >> 4];
            temp_autolink[temp_autolink_len++] = hex[slaveDevInfo[i].PeerAddr[3] & 0x0F];
            temp_autolink[temp_autolink_len++] = hex[slaveDevInfo[i].PeerAddr[2] >> 4];
            temp_autolink[temp_autolink_len++] = hex[slaveDevInfo[i].PeerAddr[2] & 0x0F];
            temp_autolink[temp_autolink_len++] = hex[slaveDevInfo[i].PeerAddr[1] >> 4];
            temp_autolink[temp_autolink_len++] = hex[slaveDevInfo[i].PeerAddr[1] & 0x0F];
            temp_autolink[temp_autolink_len++] = hex[slaveDevInfo[i].PeerAddr[0] >> 4];
            temp_autolink[temp_autolink_len++] = hex[slaveDevInfo[i].PeerAddr[0] & 0x0F];
            temp_autolink[temp_autolink_len++] = '>';
            temp_autolink[temp_autolink_len++] = '\r';
            temp_autolink[temp_autolink_len++] = '\n';
            if(slaveDevInfo[i].AutoConnection == 1)
            {
                conneNum ++;
            }
            //while(HalUartGetTxReady(UART1) == ERR_BUSY);
            //HalUartSendBuf(UART1, temp_autolink, temp_autolink_len);
            at_send_data(at_data.data_type,temp_autolink,temp_autolink_len);
            temp_autolink_len = 0;
        }
        //uint8_t conneNum = GAP_NumActiveConnections() + 0x30;
        conneNum += 0x30;
        reply_at_data("AUTOLINK:", 9, &conneNum, 1);
    }
    else if(temp_data == 2)
    {
        //没输入mac地址,并且该通道没写过地址
        if((osal_memcmp(temp_mac_null,slaveDevInfo[temp_channel].PeerAddr,6)))
        {
            LOG("1 NULL\n");
            return;//无事发生
        }
        else 
        {
            at_white_list_enable(temp_channel,temp_enable);
            reply_ok(at_data.data_type);
        }
    }
    else if(temp_data == 3)
    {

        for(int i = 0 ; i < g_slaveMaxNum ; i ++)//先检查写的地址，有没有和以前重复
        {
            //LOG("osal_memcmp(addr,slaveDevInfo[%d].PeerAddr,6)= %d -\n",i,osal_memcmp(addr,slaveDevInfo[i].PeerAddr,6));
            if(osal_memcmp(temp_mac,slaveDevInfo[i].PeerAddr,6)&&(slaveDevInfo[i].ConnectionHandle == 0xff))//已重复
            {
                
                if(i != temp_channel)
                {
                    //输入的地址已存在于其他通道，则删除原来存的通道号，填上新的通道号，同时要使能才响应
                    LOG(" repeat! dic i=%d\n",i);
                    osal_memcpy(slaveDevInfo[i].PeerAddr, temp_mac_null, B_ADDR_LEN);//清空
                    slaveDevInfo[i].PeerAddrType = LL_DEV_ADDR_TYPE_PUBLIC;
                    slaveDevInfo[i].ConnectionHandle = 0xFF;
                    slaveDevInfo[i].ConnectionState = 0;
                    slaveDevInfo[i].ConnectionActive = 0;

                    osal_memcpy(slaveDevInfo[temp_channel].PeerAddr, temp_mac, B_ADDR_LEN);
                    slaveDevInfo[temp_channel].PeerAddrType = LL_DEV_ADDR_TYPE_PUBLIC;
                    slaveDevInfo[temp_channel].ConnectionHandle = 0xFF;
                    slaveDevInfo[temp_channel].ConnectionState = 0;
                    slaveDevInfo[temp_channel].ConnectionActive = 0;
                }

                at_white_list_enable(temp_channel,temp_enable);
                reply_ok(at_data.data_type);

                return;
            }
            else if(osal_memcmp(temp_mac,slaveDevInfo[i].PeerAddr,6)&&(slaveDevInfo[i].ConnectionHandle != 0xff))
            {
                if(i == temp_channel)//通道号相同则允许控制自动连接
                {
                    at_white_list_enable(temp_channel,temp_enable);
                    reply_ok(at_data.data_type);
                }
                //输入的地址已存在于 其他 通道但是那个通道还连着，就不允许更改
                LOG(" repeat! connect i=%d\n",i);
                return;
            }
        }

        if((osal_memcmp(temp_mac_null,slaveDevInfo[temp_channel].PeerAddr,6)))//该通道为空
        {
            osal_memcpy(slaveDevInfo[temp_channel].PeerAddr, temp_mac, B_ADDR_LEN);    
            slaveDevInfo[temp_channel].PeerAddrType = LL_DEV_ADDR_TYPE_PUBLIC;
            slaveDevInfo[temp_channel].ConnectionHandle = 0xFF;
            slaveDevInfo[temp_channel].ConnectionState = 0;
            slaveDevInfo[temp_channel].ConnectionActive = 0;
            at_white_list_enable(temp_channel,temp_enable);
            reply_ok(at_data.data_type);
        }
        else if((osal_memcmp(temp_mac_null,slaveDevInfo[temp_channel].PeerAddr,6) == 0))//要写的通道存在设备了,不允许设置
        {
            LOG("8 NULL\n");
            return;//无事发生
        }

        //temp_channel = writeConnectIndexByAddr(temp_mac);//将man地址写入全局变量保存
    }
}

void at_clrlink(uint8_t *data,uint8_t len)
{
    uint8_t temp_data = 0;
    uint8_t temp_null_mac[6]={0};
    temp_data = get_at_data_1byte(data,len);
    if((temp_data > 7)&&(temp_data != AT_CMD_FIND)||(temp_data == AT_CMD_ERROR))
    {
        LOG("at_clrlink error\n");
        return;
    }
    uint8_t temp_mode = ble_get_at_mode();
    if(temp_mode == BLE_ONLY_SLAVE)
    {
        LOG("at_clrlink error!\n");
        return;
    }
    LOG("at_clrlink %d\n",temp_data);
    if(temp_data == AT_CMD_FIND)
    {

        for(int i = 0 ; i < g_slaveMaxNum ; i++)
        {
            at_white_list_enable(i,0);
            osal_memcpy(slaveDevInfo[i].PeerAddr, temp_null_mac, B_ADDR_LEN);    
            slaveDevInfo[i].PeerAddrType = LL_DEV_ADDR_TYPE_PUBLIC;
            slaveDevInfo[i].ConnectionHandle = 0xFF;
            slaveDevInfo[i].ConnectionState = 0;
            slaveDevInfo[i].ConnectionActive = 0;
        }
        GAPMultiRole_TerminateConnection(GAP_CONNHANDLE_INIT);
        GAPMultiRole_TerminateConnection(GAP_CONNHANDLE_ALL);
        reply_ok(at_data.data_type);
    }
    else
    {
        at_white_list_enable(temp_data,0);
        GAPMultiRole_TerminateConnection(slaveDevInfo[temp_data].ConnectionHandle);
        osal_memcpy(slaveDevInfo[temp_data].PeerAddr, temp_null_mac, B_ADDR_LEN);    
        slaveDevInfo[temp_data].PeerAddrType = LL_DEV_ADDR_TYPE_PUBLIC;
        slaveDevInfo[temp_data].ConnectionHandle = 0xFF;
        slaveDevInfo[temp_data].ConnectionState = 0;
        slaveDevInfo[temp_data].ConnectionActive = 0;
        reply_ok(at_data.data_type);
    }
}

uint8_t at_get_service_data(uint8_t *data,uint8_t len,ble_service_t *service)
{
    uint8_t temp_num = 0;
    for(int i = 0 ; i < len ; i ++)//查找参数个数
    {
        if(*(data + i) == '<')
        {
            temp_num ++;
            switch(temp_num)
            {
                case 1:
                    if(*(data + i + 2) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                    if( str_to_hex(*(data + i + 1)) >= 2)
                    {
                        return AT_CMD_ERROR;
                    }
                    service->flag = str_to_hex(*(data + i + 1));
                        
                    break;
                case 2:
                    if(*(data + i + 5) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                    service->main_service[0] = ((str_to_hex(*(data + i + 1))<<4)|(str_to_hex(*(data + i + 2))&0x0F));
                    service->main_service[1] = ((str_to_hex(*(data + i + 3))<<4)|(str_to_hex(*(data + i + 4))&0x0F));
                    
                    
                    break;
                case 3:
                    if(*(data + i + 5) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                    service->notify[0] = ((str_to_hex(*(data + i + 1))<<4)|(str_to_hex(*(data + i + 2))&0x0F));
                    service->notify[1] = ((str_to_hex(*(data + i + 3))<<4)|(str_to_hex(*(data + i + 4))&0x0F));
                    
                    
                    
                    break;
                case 4:
                    if(*(data + i + 5) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                    service->wr[0] = ((str_to_hex(*(data + i + 1))<<4)|(str_to_hex(*(data + i + 2))&0x0F));
                    service->wr[1] = ((str_to_hex(*(data + i + 3))<<4)|(str_to_hex(*(data + i + 4))&0x0F));
                    
                    
                    break;
                case 5:
                    if(*(data + i + 5) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                    service->at[0] = ((str_to_hex(*(data + i + 1))<<4)|(str_to_hex(*(data + i + 2))&0x0F));
                    service->at[1] = ((str_to_hex(*(data + i + 3))<<4)|(str_to_hex(*(data + i + 4))&0x0F));
                    //LOG_DUMP_BYTE(service->at,2);
                    
                    break;
                case 6:
                    //LOG("i %d\n",i);
                    if(service->flag == 0)
                    {
                        return AT_CMD_ERROR;
                    }
                    if(*(data + i + 33) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                    for(int j = 0 ; j <16 ; j++)//基础UUID长度为128bit=16字节
                    {
                        //LOG("(str_to_hex(*(data + i + 2*j+1))<<4) %02x (str_to_hex(*(data + i + 2*j+2))&0x0F) %02x\n",(str_to_hex(*(data + i + 2*j+1))<<4),(str_to_hex(*(data + i + 2*j+2))&0x0F));
                        service->bit128_base[j] = ((str_to_hex(*(data + i + 2*j+1))<<4)|(str_to_hex(*(data + i + 2*j+2))&0x0F));
                    }
                    //LOG_DUMP_BYTE(service->bit128_base,16);
                    
                    
                    break;
            }
            
            
        }
        else if((i == len - 1)&&(temp_num == 0))//没找到参数，表示查询
        {
            
            return AT_CMD_FIND;
        }
    }
    if((service->flag == 1)&&(temp_num !=6))
    {
        return AT_CMD_ERROR;
    }
    

    return AT_CMD_SUCCES;
}

void at_service(uint8_t *data,uint8_t len)
{
    ble_service_t service;
    uint8_t ret = 0;
    uint8_t temp_service[64] = {0};
    uint8_t temp_service_len = 0;
    char hex[] = "0123456789ABCDEF";
    //static uint8_t service_flag = 0;
    ret = at_get_service_data(data, len, &service);
    LOG("service.flag %d\n",service.flag);
    if(ret == AT_CMD_ERROR)
    {
        LOG("at_service error !");
        //osal_memset(&service, 0, sizeof(ble_service_t));
        return;
    }
    uint8_t temp_mode = ble_get_at_mode();
    if(temp_mode == BLE_ONLY_MASTER)//主机模式下不允许设置服务
    {
        return;
    }
    if(ret == AT_CMD_FIND)
    {
        ble_service_t read_service;
        ble_get_custom_serviceUUID( &read_service);
        temp_service[temp_service_len++] = 'S';
        temp_service[temp_service_len++] = 'E';
        temp_service[temp_service_len++] = 'R';
        temp_service[temp_service_len++] = 'V';
        temp_service[temp_service_len++] = 'I';
        temp_service[temp_service_len++] = 'C';
        temp_service[temp_service_len++] = 'E';
        temp_service[temp_service_len++] = ':';
        temp_service[temp_service_len++] = '<';
        temp_service[temp_service_len++] = read_service.flag + 0x30;
        temp_service[temp_service_len++] = '>';
        temp_service[temp_service_len++] = ',';
        temp_service[temp_service_len++] = '<';
        temp_service[temp_service_len++] = hex[read_service.main_service[0]>> 4];
        temp_service[temp_service_len++] = hex[read_service.main_service[0]& 0x0F];
        temp_service[temp_service_len++] = hex[read_service.main_service[1]>> 4];
        temp_service[temp_service_len++] = hex[read_service.main_service[1]& 0x0F];
        temp_service[temp_service_len++] = '>';
        temp_service[temp_service_len++] = ',';
        temp_service[temp_service_len++] = '<';
        temp_service[temp_service_len++] = hex[read_service.notify[0]>> 4];
        temp_service[temp_service_len++] = hex[read_service.notify[0]& 0x0F];
        temp_service[temp_service_len++] = hex[read_service.notify[1]>> 4];
        temp_service[temp_service_len++] = hex[read_service.notify[1]& 0x0F];
        temp_service[temp_service_len++] = '>';
        temp_service[temp_service_len++] = ',';
        temp_service[temp_service_len++] = '<';
        temp_service[temp_service_len++] = hex[read_service.wr[0]>> 4];
        temp_service[temp_service_len++] = hex[read_service.wr[0]& 0x0F];
        temp_service[temp_service_len++] = hex[read_service.wr[1]>> 4];
        temp_service[temp_service_len++] = hex[read_service.wr[1]& 0x0F];
        temp_service[temp_service_len++] = '>';
        temp_service[temp_service_len++] = ',';
        temp_service[temp_service_len++] = '<';
        temp_service[temp_service_len++] = hex[read_service.at[0]>> 4];
        temp_service[temp_service_len++] = hex[read_service.at[0]& 0x0F];
        temp_service[temp_service_len++] = hex[read_service.at[1]>> 4];
        temp_service[temp_service_len++] = hex[read_service.at[1]& 0x0F];
        temp_service[temp_service_len++] = '>';

        if(read_service.flag == 0)
        {
            temp_service[temp_service_len++] = '\r';
            temp_service[temp_service_len++] = '\n';

        }
        else if(read_service.flag == 1)
        {
            temp_service[temp_service_len++] = ',';
            temp_service[temp_service_len++] = '<';
            for(int i = 0 ; i < 16 ; i++)
            {
                temp_service[temp_service_len++] = hex[read_service.bit128_base[i]>> 4];
                temp_service[temp_service_len++] = hex[read_service.bit128_base[i]& 0x0F];
            }
            temp_service[temp_service_len++] = '>';
            temp_service[temp_service_len++] = '\r';
            temp_service[temp_service_len++] = '\n';
        }
        //while(HalUartGetTxReady(UART1) == ERR_BUSY);
        //HalUartSendBuf(UART1, temp_service, temp_service_len);
        at_send_data(at_data.data_type,temp_service,temp_service_len);
        temp_service_len = 0;

    }
    else
    {
        bleuart_DeleteService();
        //service_flag = service.flag;
        //for(int i = 0 ; i < g_masterMaxNum ; i ++)//断开所有主机
        {
        //    GAPMultiRole_TerminateConnection(masterDevInfo[i].ConnectionHandle);
        }
        GAPMultiRole_TerminateConnection(GAP_CONNHANDLE_INIT);//断开所有设备
        GAPMultiRole_TerminateConnection(GAP_CONNHANDLE_ALL);
        if(service.flag == 0)
        {
            LOG("2 byte!\n");
            ble_set_custom_serviceUUID(ATT_BT_UUID_SIZE,service);
           // ble_AddCustomService(ATT_BT_UUID_SIZE);
           bleuart_AddService();
        }
        else if(service.flag == 1)
        {
            LOG("16 byte!\n");
            ble_set_custom_serviceUUID(ATT_UUID_SIZE,service);
            bleuart_AddService();
           // ble_AddCustomService(ATT_UUID_SIZE);
        }
        reply_ok(at_data.data_type);
    }
            
    LOG("*service.flag  %d\n",service.flag);
    LOG("service :");
    LOG_DUMP_BYTE(service.main_service,2);
    LOG("notify :");
    LOG_DUMP_BYTE(service.notify,2);
    LOG("wr :");
    LOG_DUMP_BYTE(service.wr,2);
    LOG("bit128_base :");
    LOG_DUMP_BYTE(service.bit128_base,16);
}

uint8_t at_get_txhandle_data(uint8_t *data,uint8_t len,uint8_t *role, uint8_t *channel)
{

    for(int i = 0 ; i < len ; i ++)
    {
        if(*(data+i) == '<')//找到'<'
        {
            *role = *(data+i+1);
            *channel = *(data+i+5);
            
            if((*(data+i+2) != '>')&&(*(data+i+6) != '>'))
            {
                return AT_CMD_ERROR;
            } 

            if((*channel < '0')||(*channel > '7'))//限制通道号
            {
                return AT_CMD_ERROR;
            }

            if((*role != 'M')&&(*role != 'S'))//限制字符
            {
                return AT_CMD_ERROR;
            }
            break;
        }
        else if(i == len-1)
        {

            return AT_CMD_ERROR;
        }
    }
    return AT_CMD_SUCCES;
}
//设置透传方向
void at_txhandle(uint8_t *data,uint8_t len)
{
    uint8_t temp_role = 0;
    uint8_t temp_channel = 0;
    
    uint8_t ret = at_get_txhandle_data(data, len, &temp_role, &temp_channel);
    //LOG("txhandle ret %d role %c channel %d\n",ret,temp_role,temp_channel);
    if(ret == AT_CMD_ERROR)
    {
        return;
    }
    uint8_t temp_mode = ble_get_at_mode();
    if(temp_mode == BLE_ONLY_SLAVE)//从机模式下不允许设置数据方向
    {
        LOG("txhnadle mode error!\n");
        return;
    }
    else if((temp_mode == BLE_ONLY_MASTER)&&(temp_role == 'M'))//主机模式下不允许设置方向走向主机
    {
        LOG("txhnadle mode error!!\n");
        return;
    }
    
    temp_channel -= 0x30;
    at_data.ble_send_index = temp_channel;

    if((temp_role == 'M')&&(at_data.ble_send_index <g_masterMaxNum))//masterDevInfo
    {      
        at_data.ble_send_role = AT_MASTER;
        reply_ok(at_data.data_type);
    }
    else if((temp_role == 'S')&&(at_data.ble_send_index <g_slaveMaxNum))
    {
        at_data.ble_send_role = AT_SLAVE;
        reply_ok(at_data.data_type);
    }
    
    LOG("txhandl index %d role %d \n",at_data.ble_send_index,at_data.ble_send_role);
}
//获取桥接数据
uint8_t at_get_bridge_data(uint8_t *data,uint8_t len,at_bridge_t *bridge,uint8_t *channel)
{
    uint8_t temp_num = 0;
    for(int i = 0 ; i < len ; i ++)//查找参数个数
    {
        if(*(data + i) == '<')
        {
            temp_num ++;
            switch(temp_num)
            {
                case 1:
                    *channel = str_to_hex(*(data + i + 1));
                    
                    if(*(data + i + 2) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                        
                    break;
                case 2:
                    bridge->bridge_enable = str_to_hex(*(data + i + 1));
                    
                    if(*(data + i + 2) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                        
                    break;
                case 3:
                    bridge->in_role = *(data + i + 1);
                    
                    if(*(data + i + 2) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                        
                    break;
                case 4:
                    bridge->in_role_index = str_to_hex(*(data + i + 1));
                    
                    if(*(data + i + 2) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                    break;
                case 5:
                    bridge->out_role = *(data + i + 1);
                    
                    if(*(data + i + 2) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                    break;
                case 6:
                    bridge->out_role_index = str_to_hex(*(data + i + 1));
                    
                    if(*(data + i + 2) != '>')
                    {
                        return AT_CMD_ERROR;
                    }
                    break;
            }
        }
        else if((i == len - 1)&&(temp_num == 0))//没找到参数，表示查询
        {
            
            return AT_CMD_FIND;
        }
    }

    return temp_num;
}
//桥接命令数据处理
uint8_t at_bridge_deal(uint8_t role,uint8_t index,attMsg_t *sendMsg)
{
    for(int i = 0 ; i <AT_BRIDGE_NUM; i++)
    {
        //LOG("user_data.bridge[i].bridge_enable %d\n",user_data.bridge[i].bridge_enable);
        //LOG("user_data.bridge[i].in_role %c\n",user_data.bridge[i].in_role);
        //LOG("user_data.bridge[i].out_role %c\n",user_data.bridge[i].out_role);
        //LOG("role %d\n",role);
        if(user_data.bridge[i].bridge_enable == 1)//如果有桥接设置使能
        {
            if((user_data.bridge[i].in_role == 'M')&&(user_data.bridge[i].out_role == 'M'))
            {
                if((index == user_data.bridge[i].in_role_index)&&(role == AT_MASTER))
                {   
                    //LOG("M -> M\n");
                    user_data_send_by_ble(LL_ROLE_SLAVE,user_data.bridge[i].out_role_index, sendMsg);
                    return AT_CMD_SUCCES;
                }
                else if((index == user_data.bridge[i].out_role_index)&&(role == AT_MASTER))
                {   
                    //LOG("-M -> M\n");
                    user_data_send_by_ble(LL_ROLE_SLAVE,user_data.bridge[i].in_role_index, sendMsg);
                    return AT_CMD_SUCCES;
                }
                else
                {
                    return AT_NULL_BRIDGE;
                }
            }
            else if((user_data.bridge[i].in_role == 'M')&&(user_data.bridge[i].out_role == 'S'))
            {
                //LOG("index %d,role %d\n",index,role);
                if((index == user_data.bridge[i].in_role_index)&&(role == AT_MASTER))
                {   
                    //LOG("M -> S i=%d idx %d\n",i,user_data.bridge[i].out_role_index);
                    user_data_send_by_ble(LL_ROLE_MASTER,user_data.bridge[i].out_role_index,sendMsg);
                    return AT_CMD_SUCCES;
                }
                else if((index == user_data.bridge[i].out_role_index)&&(role == AT_SLAVE))
                {
                    //LOG("S -> M i=%d idx %d\n",i,user_data.bridge[i].in_role_index);
                    user_data_send_by_ble(LL_ROLE_SLAVE,user_data.bridge[i].in_role_index,sendMsg);
                    return AT_CMD_SUCCES;
                }
                else
                {
                    return AT_NULL_BRIDGE;
                }
            }
            else if((user_data.bridge[i].in_role == 'S')&&(user_data.bridge[i].out_role == 'M'))
            {
                if((index == user_data.bridge[i].in_role_index)&&(role == AT_SLAVE))
                {   
                    //LOG("S -> M\n");
                    user_data_send_by_ble(LL_ROLE_SLAVE,user_data.bridge[i].out_role_index,sendMsg);
                    return AT_CMD_SUCCES;
                }
                else if((index == user_data.bridge[i].out_role_index)&&(role == AT_MASTER))
                {
                    //LOG("-M -> S\n");
                    user_data_send_by_ble(LL_ROLE_MASTER,user_data.bridge[i].in_role_index,sendMsg);
                    return AT_CMD_SUCCES;
                }
                else
                {
                    return AT_NULL_BRIDGE;
                }
            }
            else if((user_data.bridge[i].in_role == 'S')&&(user_data.bridge[i].out_role == 'S'))
            {
                if((index == user_data.bridge[i].in_role_index)&&(role == AT_SLAVE))
                {   
                    //LOG("S -> S\n");
                    user_data_send_by_ble(LL_ROLE_MASTER,user_data.bridge[i].out_role_index,sendMsg);
                    return AT_CMD_SUCCES;
                }
                else if((index == user_data.bridge[i].out_role_index)&&(role == AT_SLAVE))
                {
                    //LOG("S -> S\n");
                    user_data_send_by_ble(LL_ROLE_MASTER,user_data.bridge[i].in_role_index,sendMsg);
                    return AT_CMD_SUCCES;
                }
                else
                {
                    return AT_NULL_BRIDGE;
                }
            }
            else
            {
                return AT_NULL_BRIDGE;
            }
        }
    }
    return AT_NULL_BRIDGE;
}
//桥接命令
void at_bridge(uint8_t *data,uint8_t len)
{   
    at_bridge_t temp_bridge=
    {
        .in_role = 0,
        .out_role = 0,
        .in_role_index = 0,
        .out_role_index = 0,
        .bridge_enable = 0,
    };
    uint8_t temp_channel = 0;
    uint8_t temp_mode = ble_get_at_mode();
    uint8_t ret = 0;
    
    ret = at_get_bridge_data(data,len,&temp_bridge,&temp_channel);
    LOG("bridge %d temp_mode %d in %c out %c\n",ret, temp_mode, temp_bridge.in_role, temp_bridge.out_role);
    if(temp_mode == BLE_ONLY_SLAVE)//单从机下不允许操作
    {
        LOG("BLE_ONLY_SLAVE mode no bridge error!\n");
        return;
    }
    else if((temp_mode == BLE_ONLY_MASTER)&&((temp_bridge.in_role=='M')||(temp_bridge.out_role=='M')))//主机模式下不允许设置桥接到中心设备的主机
    {
        LOG("2 bridge error!!\n");
        return;
    }

    if((ret == AT_CMD_ERROR)||(temp_channel >= AT_BRIDGE_NUM))
    {
        LOG("3 bridge error!!!\n");
        return;
    }

    if(temp_bridge.bridge_enable > 1)
    {
        LOG("- bridge error!!!\n");
        return;
    }

    if((temp_bridge.in_role=='M')&&(temp_bridge.in_role_index>g_masterMaxNum-1))
    {
        LOG("3 bridge error!!!!\n");
        return;
    }

    if((temp_bridge.out_role=='M')&&(temp_bridge.out_role_index>g_masterMaxNum-1))
    {
        LOG("4 bridge error!!!!!\n");
        return;
    }

    if((temp_bridge.in_role=='S')&&(temp_bridge.in_role_index>g_slaveMaxNum-1))
    {
        LOG("5 bridge error!!!!!!\n");
        return;
    }

    if((temp_bridge.out_role=='S')&&(temp_bridge.out_role_index>g_slaveMaxNum-1))
    {
        LOG("6 bridge error!!!!!!\n");
        return;
    }

    if((ret != AT_CMD_FIND)&&(temp_bridge.out_role==temp_bridge.in_role)&&(temp_bridge.out_role_index == temp_bridge.in_role_index))
    {
        LOG("7 bridge error!!!!!!\n");
        return;
    }

    if(ret == AT_CMD_FIND)
    {
        uint8_t temp_bridge_data[30];
        uint8_t temp_bridge_data_len = 0;
        uint8_t temp_data = 0;
        reply_ok(at_data.data_type);
        for(int i = 0 ; i < AT_BRIDGE_NUM ; i ++)
        {
            if((user_data.bridge[i].in_role == 'M')||(user_data.bridge[i].in_role == 'S'))
            {
                if(user_data.bridge[i].bridge_enable == 1)//计算已经使能的桥接模式
                {
                    temp_data++;
                }
            }
            temp_bridge_data[temp_bridge_data_len++] = '<';
            temp_bridge_data[temp_bridge_data_len++] = i+0x30;
            temp_bridge_data[temp_bridge_data_len++] = '>';
            temp_bridge_data[temp_bridge_data_len++] = ',';
            temp_bridge_data[temp_bridge_data_len++] = '<';
            temp_bridge_data[temp_bridge_data_len++] = user_data.bridge[i].in_role;
            temp_bridge_data[temp_bridge_data_len++] = '>';
            temp_bridge_data[temp_bridge_data_len++] = ',';
            temp_bridge_data[temp_bridge_data_len++] = '<';
            temp_bridge_data[temp_bridge_data_len++] = user_data.bridge[i].in_role_index + 0x30;
            temp_bridge_data[temp_bridge_data_len++] = '>';
            temp_bridge_data[temp_bridge_data_len++] = ',';
            temp_bridge_data[temp_bridge_data_len++] = '<';
            temp_bridge_data[temp_bridge_data_len++] = user_data.bridge[i].out_role;
            temp_bridge_data[temp_bridge_data_len++] = '>';
            temp_bridge_data[temp_bridge_data_len++] = ',';
            temp_bridge_data[temp_bridge_data_len++] = '<';
            temp_bridge_data[temp_bridge_data_len++] = user_data.bridge[i].out_role_index + 0x30;
            temp_bridge_data[temp_bridge_data_len++] = '>';
            temp_bridge_data[temp_bridge_data_len++] = ',';
            temp_bridge_data[temp_bridge_data_len++] = '<';
            temp_bridge_data[temp_bridge_data_len++] = user_data.bridge[i].bridge_enable + 0x30;
            temp_bridge_data[temp_bridge_data_len++] = '>';
            temp_bridge_data[temp_bridge_data_len++] = '\r';
            temp_bridge_data[temp_bridge_data_len++] = '\n';
            //LOG("user_data.bridge[i].in_role + 0x30; %d\n",user_data.bridge[i].in_role );
            //while(HalUartGetTxReady(UART1) == ERR_BUSY);
            //HalUartSendBuf(UART1, temp_bridge_data, temp_bridge_data_len);
            at_send_data(at_data.data_type,temp_bridge_data,temp_bridge_data_len);
            temp_bridge_data_len = 0;
        }
        temp_data += 0x30;
        reply_at_data("BRIDGE:",7,&temp_data,1);
    }
    else
    {
        if(ret == 2)
        {
            if(((user_data.bridge[temp_channel].in_role != 'M' )&&(user_data.bridge[temp_channel].in_role != 'S' ))||((user_data.bridge[temp_channel].out_role != 'M' )&&(user_data.bridge[temp_channel].out_role != 'S' )))
            {
                LOG("null error! \n");
                return ;//无事发生
            }
            else
            {
                user_data.bridge[temp_channel].bridge_enable = temp_bridge.bridge_enable;
                reply_ok(at_data.data_type);
            }
        }
        else if(ret == 6)
        {
            
            for(int i = 0 ; i < AT_BRIDGE_NUM ; i++)
            {
                //先查询设置的桥接是否存在,如果存在则只控制开关
                if(i!=temp_channel)
                {
                    if(((user_data.bridge[i].in_role == temp_bridge.in_role)&&(user_data.bridge[i].in_role_index == temp_bridge.in_role_index))\
                    ||((user_data.bridge[i].out_role == temp_bridge.out_role)&&(user_data.bridge[i].out_role_index == temp_bridge.out_role_index))\
                    ||((user_data.bridge[i].in_role == temp_bridge.out_role)&&(user_data.bridge[i].in_role_index == temp_bridge.out_role_index)) \
                    || ((user_data.bridge[i].out_role == temp_bridge.in_role)&&(user_data.bridge[i].out_role_index == temp_bridge.in_role_index)))
                    {
                        return;//然后结束
                    }
                }
            }
        }
        
        //user_data.bridge_channel ++;
        user_data.bridge[temp_channel].in_role = temp_bridge.in_role;
        user_data.bridge[temp_channel].in_role_index = temp_bridge.in_role_index;
        user_data.bridge[temp_channel].out_role = temp_bridge.out_role;
        user_data.bridge[temp_channel].out_role_index = temp_bridge.out_role_index;
        user_data.bridge[temp_channel].bridge_enable = temp_bridge.bridge_enable;
        LOG("-bridge[%d].in_role = %c\n",temp_channel,user_data.bridge[temp_channel].in_role);
        LOG("-bridge[%d].in_role_index = %d\n",temp_channel,user_data.bridge[temp_channel].in_role_index);
        LOG("-bridge[%d].out_role = %c\n",temp_channel,user_data.bridge[temp_channel].out_role);
        LOG("-bridge[%d].out_role_index = %d\n",temp_channel,user_data.bridge[temp_channel].out_role_index);
        LOG("-bridge[%d].bridge_enable = %d\n",temp_channel,user_data.bridge[temp_channel].bridge_enable);

        reply_ok(at_data.data_type);
        user_data_save();
        
    }
}
//取消桥接命令
void at_clrbridge(uint8_t *data,uint8_t len)
{
    uint8_t temp_data = 0;
    //uint8_t temp_clr = 0;
    uint8_t temp_mode = ble_get_at_mode();
    temp_data = get_at_data_1byte(data,len);
    
    if(temp_mode == BLE_ONLY_SLAVE)//单从机下不允许操作
    {
        LOG(" mode no bridge error!\n");
        return;
    }
    if(temp_data>4)
    {
        return ;//非法
    }

    user_data.bridge[temp_data].in_role = 0;
    user_data.bridge[temp_data].in_role_index = 0;
    user_data.bridge[temp_data].out_role = 0;
    user_data.bridge[temp_data].out_role_index = 0;
    user_data.bridge[temp_data].bridge_enable = 0;
    reply_ok(at_data.data_type);
    user_data_save();
}

uint8_t at_get_rssi_data(uint8_t *data, uint8_t len, int8_t *rssi )
{
    uint8_t temp_len = 0;
    for(int i = 0 ; i < len ; i ++)
    {
        if(*(data + i) == '<')
        {
            for(int j = 1 ; j < (len - i) ; j++)
            {
                if(*(data + i + j) == '>')
                {
                    temp_len = j-1;
                    LOG("temp_len %d\n",temp_len);

                    for(uint8 err_str = 1; err_str <temp_len +1; err_str ++)
                    {
                        if((*(data + i + err_str)<'0')||(*(data + i + err_str)>'9'))
                        {
                            if((err_str == 1)&&(*(data + i + err_str) == '-'))
                            {
                                
                            }
                            else 
                            {
                                LOG("error..\n");
                                return AT_CMD_ERROR;
                            }
                            
                        }
                    }
                }
                
            }

            if(temp_len == 1)
            {
                *rssi = *(data + i + 1) - 0x30; 
                return AT_CMD_SUCCES;
            }
            else if(temp_len == 2)
            {
                if(*(data + i + 1) == '-')
                {
                    if((*(data + i + 2) - 0x30) == 0)//不让设置 -0
                    {
                        return AT_CMD_ERROR;
                    }
                    *rssi = 0-(*(data + i + 2) - 0x30);
                }
                else
                {
                    *rssi = (*(data + i + 1) - 0x30)*10+(*(data + i + 2) - 0x30);
                }
                
                return AT_CMD_SUCCES;
            }
            else if(temp_len == 3)
            {
                
                if(*(data + i + 1) == '-')
                {
                    *rssi = 0 - ((*(data + i + 2) - 0x30)*10+(*(data + i + 3) - 0x30));
                }
                else
                {
                    if(((*(data + i + 2) - 0x30) >= 3)||((*(data + i + 3) - 0x30) >8))
                    {
                        return AT_CMD_ERROR;
                    }
                    *rssi = (*(data + i + 1) - 0x30)*100 + (*(data + i + 2) - 0x30)*10+(*(data + i + 3) - 0x30);
                }
                
                return AT_CMD_SUCCES;
            }
            else if(temp_len == 4)
            {

                if(*(data + i + 1) == '-')
                {
                    *rssi = 0 - ((*(data + i + 2) - 0x30)*100 + (*(data + i + 3) - 0x30)*10+(*(data + i + 4) - 0x30));
                }
                else
                {
                   // *rssi = (*(data + i + 2) - 0x30)*100 + (*(data + i + 3) - 0x30)*10+(*(data + i + 4) - 0x30);
                }
                return AT_CMD_SUCCES;
            }
            else
            {
                return AT_CMD_ERROR;
            }
        }
        else if(i == len - 1)//没找到参数，表示查询
        {
            return AT_CMD_FIND;
        }
    }
    
    return AT_CMD_SUCCES;
}

void at_rssi(uint8_t *data,uint8_t len)
{
    uint8_t ret = 0;
    int8_t temp_rssi = 0 ;
    
    ret = at_get_rssi_data(data,len,&temp_rssi);
    uint8_t temp_mode = ble_get_at_mode();
    if((ret == AT_CMD_ERROR))
    {
        LOG("set file error \n");
        return ;
    }

    if((temp_rssi > 20)||(temp_rssi < -120))
    {
        LOG("set file error !\n");
        return;
    }
    
    if(temp_mode == BLE_ONLY_SLAVE)//单从模式下不让设置
    {
        return;
    }
    LOG("temp_rssi %d\n",temp_rssi);
    if(ret == AT_CMD_FIND)
    {
        uint8_t temp_find_rssi[20] = {0} ;
        uint8_t temp_find_rssi_len = 0 ;
        uint8_t ret_rssi = 0;
        ret_rssi = get_broadcast_rssi_filt(&temp_rssi);
        LOG("temp_rssi %d ret_rssi %d\n",temp_rssi,ret_rssi);
        if(ret_rssi == FALSE)//没设置过读取失败
        {
            temp_find_rssi[temp_find_rssi_len++] = 'R';
            temp_find_rssi[temp_find_rssi_len++] = 'S';
            temp_find_rssi[temp_find_rssi_len++] = 'S';
            temp_find_rssi[temp_find_rssi_len++] = 'I';
            temp_find_rssi[temp_find_rssi_len++] = ':';
            temp_find_rssi[temp_find_rssi_len++] = '<';         
            temp_find_rssi[temp_find_rssi_len++] = 'N';
            temp_find_rssi[temp_find_rssi_len++] = 'U';
            temp_find_rssi[temp_find_rssi_len++] = 'L';
            temp_find_rssi[temp_find_rssi_len++] = 'L';
            temp_find_rssi[temp_find_rssi_len++] = '>';
            temp_find_rssi[temp_find_rssi_len++] = '\r';
            temp_find_rssi[temp_find_rssi_len++] = '\n';
        
            
        }
        else
        {
            temp_find_rssi[temp_find_rssi_len++] = 'R';
            temp_find_rssi[temp_find_rssi_len++] = 'S';
            temp_find_rssi[temp_find_rssi_len++] = 'S';
            temp_find_rssi[temp_find_rssi_len++] = 'I';
            temp_find_rssi[temp_find_rssi_len++] = ':';
            temp_find_rssi[temp_find_rssi_len++] = '<';
            if(temp_rssi >= 0)
            {
                temp_find_rssi[temp_find_rssi_len++] = (temp_rssi/ 100 % 10) + 0x30;
                temp_find_rssi[temp_find_rssi_len++] = (temp_rssi/ 10 % 10) + 0x30;
                temp_find_rssi[temp_find_rssi_len++] = (temp_rssi/ 1 % 10) + 0x30;
                temp_find_rssi[temp_find_rssi_len++] = '>';
                temp_find_rssi[temp_find_rssi_len++] = '\r';
                temp_find_rssi[temp_find_rssi_len++] = '\n';
            }
            else
            {
                temp_find_rssi[temp_find_rssi_len++] = '-';
                temp_find_rssi[temp_find_rssi_len++] = (ABS(temp_rssi)/ 100 % 10) + 0x30;
                temp_find_rssi[temp_find_rssi_len++] = (ABS(temp_rssi)/ 10 % 10) + 0x30;
                temp_find_rssi[temp_find_rssi_len++] = (ABS(temp_rssi)/ 1 % 10) + 0x30;
                temp_find_rssi[temp_find_rssi_len++] = '>';
                temp_find_rssi[temp_find_rssi_len++] = '\r';
                temp_find_rssi[temp_find_rssi_len++] = '\n';
            }

 
            
        }
        at_send_data(at_data.data_type,temp_find_rssi,temp_find_rssi_len);
        temp_find_rssi_len = 0;
        
        
    }
    else 
    {
        set_broadcast_rssi_filt(temp_rssi);
        reply_ok(at_data.data_type);
    }
   // set_broadcast_rssi_filt
}

void at_clrrssi(uint8_t *data,uint8_t len)
{
    uint8_t temp_mode = ble_get_at_mode();

    if(temp_mode == BLE_ONLY_SLAVE)//单从模式下不让设置
    {
        return;
    }

    clear_broadcast_rssi_filt();
    reply_ok(at_data.data_type);
}

